Bash scripting cheat sheet
Variables, tests, for/while loops and functions: the core Bash syntax for writing a reliable script.
Variables
name="Ana" # no space around the = echo "Hello $name" # use the variable readonly PI=3.14 # constant unset name # remove a variable
Conditions
if [ "$age" -ge 18 ]; then echo "adult" elif [ "$age" -ge 13 ]; then echo "teenager" else echo "child" fi
| Test | Meaning |
|---|---|
-eq -ne |
equal / not equal (numbers) |
-lt -le -gt -ge |
<, <=, >, >= (numbers) |
= != |
equal / not equal (strings) |
-z -n |
string is empty / non-empty |
-f -d |
file exists / directory exists |
Loops
for f in *.txt; do echo "Processing $f" done for i in {1..5}; do echo $i; done while read -r line; do echo "$line" done < file.txt
Functions and arguments
greet() {
echo "Hello $1"
}
greet "Ana"
echo "Script: $0, first argument: $1, all: $@, count: $#"
Always quote variables ("$variable") to avoid surprises with values containing spaces or empty strings. set -euo pipefail at the top of a script turns errors loud instead of silent.
Thanks for the feedback!