Bash cheatsheet
Bash cheatsheet
Troubleshooting Bash scripts
set -o nounset # Do not allow undefined variables (which default to ""). AKA "set -u"
set -o errexit # Do not ignore failing commands. AKA "set -e"
bash -n myscript.sh # syntax check/dry run of your bash script
bash -v myscripts.sh # trace of every command executed
bash -x myscript.sh # trace of the expanded command
Logical statements. Use instead []. Doublebrackets have syntactical improvements and more functionality; Use quotes around strings if need literal matching
|| logical or
&& logical and
< or > string comparison (no escaping necessary within double brackets)
-gt or -lt numerical comparison
= string equality
== string matching with globbing. "abc123" == abc* true (globbing), '$t'==''abc*'' false (literal matching)
=~ string matching with regular expressions
-n string is non-empty
-z string is empty
-eq numerical equality
-ne numerical inequality
String manipulations
slicing: ${<var>:<start>} or ${<var>:<start>:<length>}
len: "${#f}"
single subst: "${f/something/x}"
global subst: ${f//something/x}"
splitting into array: array=(${f//${DIR_SEP}/ })
Built-In Variables
$0 name of the script
$n positional parameters to script/function
$$ PID of the script
$! PID of the last command executed (and run in the background)
$? exit status of the last command (${PIPESTATUS} for pipelined commands)
$# number of parameters to script/function
$@ all parameters to script/function (sees arguments as separate word) - handles empty parameter list and white-space within parameters correctly, if quoted as "$@"
$* all parameters to script/function (sees arguments as single word)- is rarely the right choice.