Bash / Shell
Strings
Extract a substring
output="${input:$position}"
output="${input:$position:$length}"
Replace the first match of $substring
with $replacement
output="${input/$substring/$replacement}"
Replace all the matches of $substring
with $replacement
output="${input//$substring/$replacement}"
Remove shortest match of $substring
from front of $input
output="${input#$substring}"
Remove longest match of $substring
from front of $input
output="${input##$substring}"
Remove shortest match of $substring
from back of $input
output="${input%$substring}"
Remove longest match of $substring
from back of $input
output="${input%%$substring}"
Remove leading white space (left trim)
output="${input#${input%%[![:space:]]*}}"
Remove trailing white space (right trim)
output="${input%${input##*[![:space:]]}}"
Files
Check if a regular file exists
test -f "$file"
File test operators
Expression | What does it check? |
---|---|
-e | If file exists |
-f | If file exists and is a regular file |
-d | If file exists and is a directory |
-r | If file exists and is readable |
-w | If file exists and is writable |
-x | If file exists and is executable |
-s | If file exists and its size is greater than zero |
Remove filename extension
output="${file%.*}"
Logging
Merge and log stdout
and stderr
in a file:
your_program 2>&1 | tee -a log.txt
Unbuffered version:
unbuffer your_program | tee -a log.txt