Day 1: The First Script
Goal: Create a script, make it executable and start it from the
PATH, understand exit codes, useset -euo pipefailso errors don’t slip past, and use ShellCheck from the start. · Duration: approx. 60 min · Prerequisite: Day 0
Briefing
- A script is a text file with commands. The first line, the
shebang (
#!/usr/bin/env bash), tells the system which program runs it. - Every command ends with an exit code:
0means success, anything else is an error.$?holds the code of the last command.&&and||chain commands based on it. - Without precautions, a script simply keeps running after an error.
set -euo pipefailchanges that. - ShellCheck reads a script and finds typical bugs before they happen.
notes-ping ─► curl /healthz ─► exit code 0 (ok) or ≠ 0 (error)
└─► $? · && · || · set -e
Drill 1: Hello, script
source ~/sh-lab/setup/env.sh
mkdir -p ~/sh-lab/tag01 && cd ~/sh-lab/werkzeug/bin
cat > hallo <<'EOF'
#!/usr/bin/env bash
# hallo – the first script in the toolbox
echo "Hallo, $USER! Heute ist $(date +%A)."
EOF
ls -l hallo | cut -c1-10
chmod +x hallo
ls -l hallo | cut -c1-10
halloExpected:
-rw-rw-r--
-rwxrwxr-x
Hallo, ubuntu! Heute ist Monday.
cat > hallo <<'EOF' … EOFis a here document: everything up to the lineEOFends up in the file. The quotes around'EOF'prevent the shell from replacing$USERwhile writing.chmod +xmakes the file executable. Becausebin/is in thePATH,hallois enough.$(date +%A)is command substitution: the output ofdatebecomes part of the text.#!/usr/bin/env bashlooks forbashin thePATHinstead of assuming a fixed path.
bash ~/sh-lab/werkzeug/bin/hallo
bash -c '[[ 1 -eq 1 ]] && echo "bash kann [["'
sh -c '[[ 1 -eq 1 ]] && echo "sh kann [["'Expected:
Hallo, ubuntu! Heute ist Monday.
bash kann [[
sh: 1: [[: not found
With bash file, you can also start a script without
chmod +x – then the shebang doesn’t matter. With
sh file, it would run in dash, and dash doesn’t know many
Bash extensions such as [[ ]].
Save your progress? Sign up for free
Drill 2: Exit codes
true; echo "true: $?"
false; echo "false: $?"
ls /gibtsnicht 2>/dev/null; echo "ls: $?"
gibtsnicht 2>/dev/null; echo "unbekannt: $?"
curl -fsS --max-time 3 $NOTES_URL/gibtsnicht >/dev/null 2>&1; echo "curl 404: $?"Expected:
true: 0
false: 1
ls: 2
unbekannt: 127
curl 404: 22
Every program has its own codes: ls reports 2 for “not
found”, the shell 127 for an unknown command, curl -f 22
for an HTTP error. man curl lists them all.
true && echo "lief, weil true klappte"
false && echo "das erscheint nie"
false || echo "lief, weil false scheiterte"Expected:
lief, weil true klappte
lief, weil false scheiterte
Save your progress? Sign up for free
Drill 3: notes-ping
The first real tool: is notes responding?
cd ~/sh-lab/werkzeug/bin
cat > notes-ping <<'EOF'
#!/usr/bin/env bash
# notes-ping – checks whether notes responds. Exit code 0 = ok
curl -fsS --max-time 3 "$NOTES_URL/healthz" >/dev/null
EOF
chmod +x notes-ping
notes-ping; echo "Exit: $?"
docker compose -f ~/sh-lab/notes/compose.yaml stop proxy 2>&1 | tail -1
notes-ping; echo "Exit: $?"
docker compose -f ~/sh-lab/notes/compose.yaml start proxy 2>&1 | tail -1
until notes-ping 2>/dev/null; do sleep 1; done; echo "wieder da"Expected:
Exit: 0
Container notes-proxy-1 Stopped
curl: (7) Failed to connect to 127.0.0.1 port 8080 after 0 ms: Could not connect …
Exit: 7
Container notes-proxy-1 Started
wieder da
A script ends with the exit code of its last command – here, that of
curl. Without a single line of error handling,
notes-ping is already useful: in until, in
&& chains, later in cron. -f turns
HTTP errors into exit codes, -sS stays silent except on
errors.
Save your progress? Sign up for free
Drill 4: Strict mode
cd ~/sh-lab/tag01
cat > locker <<'EOF'
#!/usr/bin/env bash
cp /gibtsnicht /tmp/kopie
echo "kopiert nach ${ZIEL}/kopie"
grep -c notiz /gibtsnicht | sort
echo "Ende erreicht"
EOF
bash locker; echo "Exit: $?"Expected:
cp: cannot stat '/gibtsnicht': No such file or directory
kopiert nach /kopie
grep: /gibtsnicht: No such file or directory
Ende erreicht
Exit: 0
Three errors – and the script reports success. Now the same lines with strict mode:
sed '1a set -euo pipefail' locker > streng
head -2 streng
bash streng; echo "Exit: $?"Expected:
#!/usr/bin/env bash
set -euo pipefail
cp: cannot stat '/gibtsnicht': No such file or directory
Exit: 1
| Option | Effect |
|---|---|
-e |
Abort as soon as a command fails |
-u |
Abort on an unset variable such as $ZIEL |
-o pipefail |
A pipe fails if any part fails – not just the last one |
Try the other two errors one at a time:
bash -euc 'echo "${ZIEL}/kopie"'; echo "Exit: $?"
bash -ec 'grep -c x /gibtsnicht 2>/dev/null | sort; echo weiter'; echo "Exit: $?"
bash -ec 'set -o pipefail; grep -c x /gibtsnicht 2>/dev/null | sort; echo weiter'
echo "Exit: $?"Expected:
bash: line 1: ZIEL: unbound variable
Exit: 1
weiter
Exit: 0
Exit: 2
Without pipefail, only sort counts – and
that always works. From now on, every script in this book starts with
set -euo pipefail.
POSIX:
set -eandset -uexist everywhere;pipefailhas been standard since POSIX 2024. Oldershimplementations (including dash before 0.5.13) don’t know it.
Save your progress? Sign up for free
Drill 5: ShellCheck
cat > aufraeumen <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
dir=$1
cd $dir
rm -f *.tmp
echo Fertig in $dir
EOF
shellcheck aufraeumenExpected (shortened):
In aufraeumen line 4:
cd $dir
^--^ SC2086 (info): Double quote to prevent globbing and word splitting.
Did you mean:
cd "$dir"
In aufraeumen line 5:
rm -f *.tmp
^-- SC2035 (info): Use ./*glob* or -- *glob* so names with dashes won't …
In aufraeumen line 6:
echo Fertig in $dir
^--^ SC2086 (info): Double quote to prevent globbing and word …
…
- SC2086:
$dirwithout quotes. If the folder is calledmeine daten, the shell turns it into two words. This is the most common bug in shell scripts (Day 2). - SC2035: If a file were called
-rf.tmp,rmwould take it for an option../*.tmpturns it into a path. - Without
set -e, SC2164 would come on top: ifcdfails,rmwould run in the wrong folder. ShellCheck sees that strict mode already catches this.
Every message has a page at shellcheck.net/wiki/SCxxxx.
The corrected version:
cat > aufraeumen <<'EOF'
#!/usr/bin/env bash
set -euo pipefail
dir=$1
cd "$dir" || exit 1
rm -f ./*.tmp
echo "Fertig in $dir"
EOF
shellcheck aufraeumen && echo "ShellCheck: sauber"
mkdir -p "/tmp/meine daten" && touch "/tmp/meine daten/a.tmp" "/tmp/meine daten/b.txt"
bash aufraeumen "/tmp/meine daten" && ls "/tmp/meine daten"Expected:
ShellCheck: sauber
Fertig in /tmp/meine daten
b.txt
cd … || exit 1 does no harm anyway: it makes the intent
visible, even to readers who overlook set -e.
Save your progress? Sign up for free
Checkpoint
notes-ping && echo "notes antwortet"Expected:
notes antwortet
shellcheck ~/sh-lab/werkzeug/bin/* && echo "alles sauber"Expected:
alles sauber
head -1 ~/sh-lab/werkzeug/bin/notes-pingExpected:
#!/usr/bin/env bash
Challenge
notes-ping should run in strict mode and say something:
notes ok on stdout, and on an error
notes nicht erreichbar: <URL> on
stderr with exit code 1.
Note: >&2 redirects output to
stderr. A group { …; …; } combines several commands after
||.
Solution
cd ~/sh-lab/werkzeug/bin
cat > notes-ping <<'EOF'
#!/usr/bin/env bash
# notes-ping – checks whether notes responds. Exit code 0 = ok
set -euo pipefail
curl -fsS --max-time 3 "$NOTES_URL/healthz" >/dev/null 2>&1 \
|| { echo "notes nicht erreichbar: $NOTES_URL" >&2; exit 1; }
echo "notes ok"
EOF
shellcheck notes-ping && notes-ping
NOTES_URL=http://127.0.0.1:9 notes-ping 2>/dev/null; echo "Exit: $?"
NOTES_URL=http://127.0.0.1:9 notes-ping >/dev/nullExpected:
notes ok
Exit: 1
notes nicht erreichbar: http://127.0.0.1:9
VAR=value command sets a variable for this one call
only. The second line discards stderr and shows only the exit code, the
third discards stdout – what remains is the error message.
Save your progress? Sign up for free
Enterprise Note
- Exit codes are the interface: Monitoring, cron, CI and Kubernetes probes only evaluate them. A script that returns 0 on errors is more dangerous than no script at all.
- Errors on stderr: Only then can output and
diagnostics be separated, for example
skript > daten.txt 2>> fehler.log. - ShellCheck in CI: A pull request with ShellCheck
warnings doesn’t get through (Day 11). Exceptions are justified in the
code:
# shellcheck disable=SC2086 # weil ….