Chapter 15: Scripts and scheduling

Bash scripts and scheduling cheat sheet

The chapter on one page: what to remember, the commands to have at your fingertips, and flashcards for quick revision.

The chapter in eight sentences

Cheat sheet

Scripting

ItemDetail
First line#!/bin/bash
Make runnablechmod +x script.sh · run ./script.sh
Debugbash -x script.sh
Arguments$1 $2 · $# · "$@" · $0
Last status$? · exit 0 · exit 2
Default value${1:-default}
Substitute / calculate$(cmd) · $((a + b))
Errors to stderrecho "msg" >&2

Tests and control

ItemDetail
Files[ -f F ] -d -e -r -x -s
Numbers[ "$n" -eq|-ne|-gt|-lt|-ge|-le 3 ]
Strings[ "$s" = x ] != -z -n
Combine! · && · ||
Branchif …; then …; elif …; else …; fi
Choosecase "$1" in a) …;; *) …;; esac
Loopfor x in LIST; do …; done · while […]; do …; done
Read lineswhile IFS=: read -r a b c; do …; done < file

Scheduling

ItemDetail
crontabcrontab -e / -l / -r (-u USER as root)
System jobs/etc/cron.d/NAME: m h dom mon dow USER command
Log/var/log/cron
Trapsfull paths · redirect output · \%
Timer pairNAME.service (Type=oneshot) + NAME.timer (OnCalendar, Persistent)
Checksystemd-analyze calendar EXPR · systemctl list-timers
Onceat TIME · atq · atrm N

Flashcards

What makes a file a script you can run?
A shebang line (#!/bin/bash) and the execute bit (chmod +x).
Four ways to run a script?
./script (needs x) · bash script · name via PATH · source script (current shell)
Arguments and status?
$1 $2 … · $# count · "$@" all · $0 name · $? last exit status
Default value for a variable?
${1:-default}
Test a file, a number, a string?
[ -f F ] · [ "$n" -gt 3 ] · [ "$s" = "x" ]
if / elif / else / fi shape?
if [ … ]; then …; elif [ … ]; then …; else …; fi
Loops?
for x in LIST; do …; done · while [ … ]; do …; done
Choose between patterns?
case "$1" in start) …;; stop) …;; *) …;; esac
Fields of a crontab line?
minute hour day-of-month month day-of-week [user] command
Edit, list, remove your crontab; system jobs?
crontab -e / -l / -r · files in /etc/cron.d with a user column
Gotchas in cron?
Minimal PATH (use full paths); escape % as \%; check /var/log/cron
Timer pair?
NAME.service (Type=oneshot, ExecStart) + NAME.timer (OnCalendar, Persistent); enable --now the timer; systemctl list-timers