Bash scripting cheat sheet
Safe Bash script settings, quoting, tests, loops, functions, arguments, exit codes and text pipelines with grep, awk and sort, on one page.
Start every script like this
#!/usr/bin/env bash
set -euo pipefail
trap 'echo "failed at line $LINENO: $BASH_COMMAND" >&2' ERR
-e stop on a failure · -u an unset variable is an error · pipefail a pipe fails if any part fails.
Variables and quoting
| Write | Means |
|---|---|
name="Kestrel" | no spaces around = |
"$name" | always quote a variable |
"${name:-default}" | a default when empty or unset |
"${file%.log}" / "${path##*/}" | strip a suffix / keep the last part |
$(date +%F) | a command's output |
$(( count + 1 )) | arithmetic |
'$literal' | single quotes: no expansion |
Tests
if [[ -f "$file" ]]; then …; fi # -f file, -d dir, -e exists, -s non-empty, -x executable
[[ -z "$s" ]] [[ -n "$s" ]] # empty / not empty
[[ "$a" == "$b" ]] [[ "$s" =~ ^[0-9]+$ ]]
(( n > 10 )) # numbers
cmd && echo ok || echo failed
Loops
for f in /var/log/kestrel/*.log; do echo "$f"; done
while IFS= read -r line; do echo "$line"; done < file.txt
for i in {1..5}; do …; done
Arguments, options and exit codes
usage() { echo "usage: $0 [-n count] file" >&2; exit 2; }
count=10
while getopts "n:h" opt; do
case "$opt" in
n) count="$OPTARG" ;;
*) usage ;;
esac
done
shift $((OPTIND - 1))
[[ $# -eq 1 ]] || usage
file="$1"
$0 script · $1… arguments · $# how many · "$@" all of them, each quoted · $? last exit code · exit 0 success, non-zero failure.
Functions
log() { printf '%s %s\n' "$(date +%T)" "$*" >&2; }
backup() {
local src="$1" dest="$2"
tar -czf "$dest" -C "$src" . || return 1
}
Text pipelines
| Command | What it does |
|---|---|
| `grep -E 'ERROR | WARN' app.log` |
cut -d' ' -f1 | a field by delimiter |
awk '{print $1, $9}' access.log | fields by whitespace |
awk '$9 >= 500' access.log | rows where field 9 is 500 or more |
| `sort | uniq -c |
sed 's/old/new/g' file | replace (-i in place) |
tr 'a-z' 'A-Z' / wc -l | change characters / count lines |
Top client IPs: awk '{print $1}' access.log | sort | uniq -c | sort -rn | head -5.
Schedule it
crontab -e → 0 2 * * * /usr/local/bin/backup.sh >> /var/log/backup.log 2>&1. Check a line with the cron explainer and the script with shellcheck.