Skip to content
Hands-on IT IT Drills

Appendix A: Cheat Sheet

Everything important from Days 0–15 on a few pages. The number in parentheses is the day on which you practiced it. When in doubt, man bash, help <builtin> and www.shellcheck.net/wiki have the final word.

Skeleton of a script

#!/usr/bin/env bash
# name – what it does: name [-o value] argument…           (1, 5)
set -Eeuo pipefail                                         # (1, 10)
source "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")/../lib/lib.sh"   # (4)
trap 'die "Zeile $LINENO: $BASH_COMMAND"' ERR              # (10)
need curl jq                                               # (4)
tmp=$(mktemp) && trap 'rm -f "$tmp"' EXIT                  # (9, 10)
Exit code Meaning Day
0 success 1
1 error 1
2 incorrect usage (convention) 3
124 timeout expired 12
126 / 127 not executable / not found 1, 15
128 + n terminated by signal n (130 INT, 137 KILL, 143 TERM) 12

Variables and quoting

Expression Result Day
"$x" value, no splitting, no globbing 2
'$x' exactly $x 2
"$@" / "$*" all arguments individually / as one text 2
${x:-std} / ${x:?meldung} default value / abort if empty 2
${#x} length 2
${x#muster} / ${x##muster} remove shortest / longest piece at the front 2
${x%muster} / ${x%%muster} remove shortest / longest piece at the back 2
${x//a/b}, ${x^^}, ${x:2:3} replace, uppercase, substring 2
$(befehl) output of a command 1
$((a + b)), ((a > b)) calculate, compare (integers) 3
printf '%q' "$x" quote for a second shell 5, 14

Conditions, loops, arrays

[[ -f $f && $x == muster* && $y =~ ^[0-9]+$ ]]      # file, pattern, regex (3)
case "$x" in a | b) … ;; 2??) … ;; *) … ;; esac      # (3)
for ((i = 0; i < n; i++)); do …; done               # (3)
while IFS= read -r zeile; do …; done < datei        # read lines safely (3)
while IFS= read -r -d '' f; do …; done < <(find … -print0)   # any names (9)
liste=(a "b c"); liste+=(d); "${liste[@]}"; ${#liste[@]}       # array (5)
declare -A n; n[$k]=$((${n[$k]:-0} + 1)); "${!n[@]}"          # counting (5)
mapfile -t zeilen < <(befehl)                                 # (5)
while getopts ":u:t:vh" opt; do case "$opt" in …; esac; done; shift $((OPTIND - 1))

Text tools

Task Command Day
Count, find lines grep -c, grep -v, grep -E, grep -o, grep -F 6
Cut out a field cut -d' ' -f7 6
Frequencies sort \| uniq -c \| sort -rn \| head 6
Replace sed -E 's#/notes/[0-9]+#/notes/:id#' 7
Select lines sed -n '5p', sed '/muster/d', sed -i.bak … 7
Sum, group awk '{n[$5]++; t[$5]+=$9} END {…}' 7
Decimal numbers awk 'END {printf "%.1f", s / NR}' 7
Read JSON jq -r '.[] \| select(.text == "x") \| .id' 8
Build JSON jq -n --arg t "$text" '{text: $t}' 8
CSV jq -r '.[] \| [.id, .text] \| @csv' 8
HTTP curl -fsS --max-time 3 -w '%{http_code}' 1, 8
Find files find dir -maxdepth 1 -name 'x-*' -mtime +30 -print0 9
Parallel xargs -0 -P 4 -n 1 …, befehl & … wait "$pid" 9, 12

Operations

exec 9> datei.lock; flock -n 9 || exit 0         # only one run (10)
mv "$tmp" "$ziel"                                 # replace atomically (9)
sleep "$n" & wait $! || true                      # handle signals immediately (12)
trap 'stop=1' TERM INT; trap 'info …' USR1        # terminate in an orderly way (12)
timeout -k 5 30 befehl                            # limit run time (12)
logger -t name -p user.warning "…"                # to the journal (13)
systemctl --user daemon-reload; systemctl --user enable --now x.timer   # (13)
journalctl --user -u x -n 20 --no-pager           # (13)
rsync -az --delete -n -i quelle/ host:ziel/       # dry run (14)
ssh host bash -s -- "'arg'" < skript              # remote script (14)
ssh -R 18080:127.0.0.1:8080 host …                # tunnel (14)
cron systemd Day
*/5 * * * * OnCalendar=*:0/5 13
30 2 * * * OnCalendar=*-*-* 02:30 13
– Persistent=true (catch up on missed runs) 13
minimal environment, /bin/sh environment from Environment=, %h = home 13
output by mail or >> log 2>&1 output in the journal 13

Quality

shellcheck -x bin/*      # .shellcheckrc: source-path=SCRIPTDIR, enable=… (1, 11)
shfmt -d bin lib         # .editorconfig: indent_size, switch_case_indent (11)
bats tests               # run …; [ "$status" -eq 0 ]; [[ $output == *x* ]] (11)
bash -x skript           # tracing (4)
type -a name             # alias, function, builtin or file? (0, 15)

Failure patterns

Symptom Cause Day
bash\r: No such file or directory Windows line endings 15
command not found only in cron cron’s PATH without your own folders 13
Variable empty after … \| while the loop ran in a subshell 3, 12
wait: pid … is not a child of this shell wait in a subshell 12
File with spaces is not found variable without quotes 2, 15
Script reports 0 despite an error last command or missing pipefail 1, 15
((x++)) aborts with set -e expression was 0 → exit code 1 3
local x=$(…) swallows errors local always reports success 4
Trap reacts only after minutes foreground command blocks, & wait is missing 12
systemd ExecMainStatus=203 program in ExecStart= not found 15