Chapter 2 · Lesson 4
Intermediate
1 min read
Functions and Error Handling
Overview
Functions divide a script into named operations. Safe Bash defaults make accidental undefined variables and failed commands more visible. Error handling should identify what failed, not hide the failure.
Detailed Notes
Function
bash
log() {
printf '[%s] %s
' "$(date -u +%FT%TZ)" "$*"
}
log "Starting backup"
$* joins function arguments into one string. $@ preserves each argument separately.
Safe Bash header
bash
#!/usr/bin/env bash
set -euo pipefail
-eexits on an unhandled failing command.-utreats an undefined variable as an error.-o pipefailmakes a pipeline fail if a component fails.
set -e has exceptions and should be tested in real scripts. A command used in if, && or || may not trigger exit.
Trap cleanup
bash
tmp_dir="$(mktemp -d)"
trap 'rm -rf -- "$tmp_dir"' EXIT
echo "Working in $tmp_dir"
trap ... EXIT runs cleanup when the script exits. Quote the trap carefully so tmp_dir expands when the trap executes.
Debugging
bash
bash -x script.sh
-x prints command expansions. It can expose secrets. Never run a traced secret-producing script in a shared log system.
Common Interview Questions
Finished this lesson?
0 of 25 lessons done · 0% of the course

