Bash - cheat sheet
Contents
Arguments
| variable | description |
|---|---|
$0 |
name of the script |
$1 |
first argument |
$2 |
second argument |
$<n> |
<nth> argument, where n > 0 |
$@ |
all arguments as one string |
$# |
count of arguments |
Example
#!/bin/bash
echo script started with $# args: $@
for arg in "$@"; do
echo "$arg"
done
# $ ./script.sh --config=test --verbose 1 2
# script started with 4 args: --config=test --verbose 1 2
# --config=test
# --verbose
# 1
# 2
Brace Expansion
touch {index,blog}.{html,css}:- expands the two braces to any combination
- final command:
touch index.html index.css blog.html blog.css - no whitespaces allowed
touch {1..3}.dat:- expands to numbers inclusive from start to end with step size one
- final command:
touch 1.dat 2.dat 3.dat
Colors
Print the rainbow: for (( i = 0; i < 39; i++ )); do echo -ne "\033[0;"$i"m Normal: (0;$i); \033[1;"$i"m Light: (1;$i)\t\t\t\t\t"; done1

Prefix \033 is preferable over \x1b and \e, as its supported on more platforms.
Conditionals
if [[ <CONDITION> ]]; then
...
elif [[ <CONDITION> ]]; then
...
else
...
fi
| condition | description |
|---|---|
"$VAR" == "STRING" |
compare content of env var with string |
-z "$VAR" |
test if string length is zero |
-n "$VAR" |
test if string length is not zero |
-f "$VAR" |
test if regular file exist |
Debugging
set -x: print output of each pipeline step
Pipes and Redirects
command1 | command2: Write stdout ofcommand1to stdin ofcommand2command1 > file: Write stdout ofcommand1to file overwritingcommand1 >> file: Append stdout ofcommand1to filecommand1 > file 2>&1: Pipe stderr to stdout, append combined output to filecommand1 <<< "${VAR}": use content of env var as stdin, similar toecho ${VAR}|command1
Write multi-line text to file. EOF is an arbitrary delimiter:
cat <<EOF >> file
[Section]
key=value
another_key=3.14
EOF
- Inspired from SO