Linux Command Line · Lesson 40 of 43
Functions and exit codes
Organise Bash scripts with functions, local variables, return values and exit codes, and handle errors with set -e, trap and clear messages.
UNDERSTAND IT. THEN TRY IT.
What you can do after this lesson
You will split a script into small named pieces, report problems with proper exit codes, and make it clean up after itself. These habits are what separate a quick one-off script from one that you can trust on a server.
Defining and calling a function
A function is a named block of commands. Define it once and call it like any command:
cd ~/project
greet() {
echo "Hello, $1!"
}
greet Asha
greet "Ben Carter"Hello, Asha!
Hello, Ben Carter!Inside the function, $1, $2, $# and "$@" refer to the function's own arguments, not the script's. The syntax function greet { ... } also works in Bash, but greet() { ... } is the portable form. Define a function before the line that calls it.
Local variables
Variables are global by default: a function can read and overwrite the variables of its caller. Use local for variables that belong inside the function:
total=100
add() {
local total=0
for n in "$@"; do total=$((total + n)); done
echo "$total"
}
echo "sum: $(add 1 2 3)"
echo "outer total is still $total"sum: 6
outer total is still 100Without local, the function would have changed the outer total to 0 and then 6. As a rule, declare every variable you create inside a function as local.
Giving results back
Functions have no real return value. There are two channels:
- Output: print the result with
echoorprintfand capture it with$(function), as above. - Exit status:
return N(0 to 255) says whether it worked. Zero means success.
is_even() {
[ $(( $1 % 2 )) -eq 0 ]
}
for n in 3 4; do
if is_even "$n"; then echo "$n is even"; else echo "$n is odd"; fi
done3 is odd
4 is evenThe function's status is that of its last command, here the test, so if can use it directly. return does not carry text or large numbers, which beginners often try.
Exit codes
Every command ends with an exit code. 0 means success, and 1 to 255 mean failure, with the meaning decided by the program. grep uses 1 for "no match" and 2 for an error, and ls uses 2 when a file is missing. Common conventions:
| Code | Usual meaning |
|---|---|
| 0 | Success |
| 1 | General error |
| 2 | Misuse, such as wrong arguments |
| 126 | Found, but not executable |
| 127 | Command not found |
| 130 | Stopped with Ctrl+C |
Read the status of the last command from $? straight away, before running anything else:
grep -q ERROR logs/app.log
echo "grep found a match: status $?"
grep -q CRASH logs/app.log
echo "grep found nothing: status $?"
nonexistent-command 2>/dev/null
echo "missing command: status $?"grep found a match: status 0
grep found nothing: status 1
missing command: status 127A script ends with exit N. Without it, the script's status is the status of its last command, which is easy to get wrong, so end scripts with an explicit exit 0 when everything went well.
Reporting errors properly
Good error handling has three parts: a message on standard error, a non-zero exit code, and an early stop. A small helper function keeps scripts tidy:
cat > safe-count.sh <<'SCRIPT'
#!/bin/bash
die() {
echo "error: $*" >&2
exit 1
}
[ $# -eq 1 ] || die "usage: $0 FILE"
[ -r "$1" ] || die "cannot read $1"
echo "$1 has $(wc -l < "$1") lines"
SCRIPT
bash safe-count.sh docs/notes.txt
bash safe-count.sh nothing.txt
echo "status: $?"docs/notes.txt has 5 lines
error: cannot read nothing.txt
status: 1Failing early: set -euo pipefail
By default, a script carries on after a failing command, which can do damage: if cd build fails, the next rm -rf * runs in the wrong folder. Three settings at the top make mistakes visible:
set -e: exit immediately when a command fails.set -u: treat use of an unset variable as an error.set -o pipefail: a pipeline fails if any stage fails, not just the last.
cat > strict.sh <<'SCRIPT'
#!/bin/bash
set -euo pipefail
echo "step 1"
cp does-not-exist.txt /tmp/ 2>/dev/null
echo "step 2 (never reached)"
SCRIPT
bash strict.sh
echo "status: $?"step 1
status: 1set -e has odd corner cases, such as commands inside if conditions and in && chains, so treat it as a safety net, not a replacement for checking important steps yourself. Add || true to a command whose failure you accept.
Cleaning up with trap
A script that creates temporary files should remove them even when it fails. trap registers a command to run when the script ends or receives a signal. The pseudo-signal EXIT runs on every exit:
cat > temp-work.sh <<'SCRIPT'
#!/bin/bash
set -euo pipefail
tmp=$(mktemp)
trap 'rm -f "$tmp"; echo "cleaned up"' EXIT
echo "working in a temporary file"
sort data/fruit.txt | uniq > "$tmp"
wc -l < "$tmp"
SCRIPT
bash temp-work.shworking in a temporary file
4
cleaned upmktemp creates a safely named temporary file and prints its name. The trap's command is in single quotes so that $tmp is expanded when the trap runs, not when it is defined.
Common mistakes
Reading $? too late. Any command, including echo, resets it. Save it first: status=$?.
Expecting return to hand back text. Print the text and capture it with $().
Forgetting local. A function then silently overwrites variables elsewhere in the script.
Printing errors to standard output. Send them to standard error with >&2.
Relying on set -e alone. Check critical commands explicitly.
Exercise
Write backup.sh, which takes a folder as its argument. It should exit with a usage message when the argument is missing, fail with a clear error when the folder does not exist, create a .tar.gz of it in a temporary place with mktemp -d, print the archive name, and remove the temporary folder with a trap on EXIT. Test it with a valid folder, a missing one and no argument, and check each exit status.
KNOWLEDGE CHECK
A quick check. You’ve got this.
Try each question. Every answer comes with an explanation.
Ready for the next small win?
Mark the lesson complete when you are ready.