====== BASH - Cheat Sheet ====== ===== String Manipulation ===== ${str:position} # substring starting at position ${str:position:len} # substring starting at position with length len ${str#ubstring} # delete shortest match from front ${str##substring} # delete longest match from front ${str%substring} # delete shortest match from back ${str%%substring} # delete longest match from back ${str/pattern/replacement} # pattern replace ${str/#pattern/replacement} # pattern replace at front ${str/%pattern/replacement} # pattern replace at end ${str//pattern/replacement} # global pattern replace ---- ===== Parameter Substituion ===== ${str-default} # set 'default' if not set ${str:-default} # set 'default' if not set (even if declared null) ${str=default} # set 'default' if not set ${str:=default} # set 'default' if not set (even if declared null) ${str+value} # set 'value' if $str is set, otherwise set null ${str:+value} # set 'value' if $str is set (even if declared null), otherwise set null ${str?error} # abort with 'error' if not set ${str:?error} # abort with 'error' if not set (and not null) ---- ===== Arrays ===== Indexed arrays require no declaration arr=("string 1", "string 2", "string 3") arr=([1]="string 1", [2]="string 2", [3]="string 3") arr[4]="string 4" Check below under "Hashes" for accessing the different properties of an array. ---- ===== Hashes ===== Since Bash v4 # Hashes need declaration! declare -A arr # Assigning values to associative arrays arr[my key]="my value" arr["my key"]="my value" arr[$my_key]="my value" # Fetching values echo ${arr[my key]} echo ${arr["my key"]} echo ${arr[$my_key]} # Accessing the array ${arr[@]} # Returns all indizes and their items (doesn't work with associative arrays) ${arr[*]} # Returns all items ${!arr[*]} # Returns all indizes ${#arr[*]} # Number elements ${#arr[$n]} # Length of $nth item # Pushing to array arr+=("new string value", "another new value") ---- ===== Here Documents ===== Bash allows here documents like this cat < To disable substitution in the here doc text quote the marker with single or double quotes. cat <<'EOT' To strip leading tabs use cat <<-EOT ---- ===== Debugging Scripts ===== For simple tracing add a set -x in the script or append the "-x" to the shebang or run the script like this: bash -x