This Bash scripting cheat sheet covers shell script syntax — variables, conditionals, loops, functions and special variables.
Variables & conditionals
| Code | What it does |
|---|---|
| name="Tom" | Set a variable |
| echo "$name" | Use a variable |
| if [ "$x" -gt 5 ]; then | Numeric comparison |
| [ -f file ] | True if file exists |
| [ -z "$s" ] | True if string is empty |
| $( command ) | Command substitution |
Loops, functions & specials
| Code | What it does |
|---|---|
| for i in 1 2 3; do | For loop |
| while [ $x -lt 5 ]; do | While loop |
| greet() { echo hi; } | Define a function |
| $? | Exit status of last command |
| $# | Number of arguments |
| $@ | All arguments |
| $0 | Script name |