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

ExpressionWhat does it check?
-eIf file exists
-fIf file exists and is a regular file
-dIf file exists and is a directory
-rIf file exists and is readable
-wIf file exists and is writable
-xIf file exists and is executable
-sIf 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