Linux › Section K · Shell scripts › Topic K.2
Special variables and exit codes
A script becomes a real tool when it can take arguments and report whether it worked. The shell's special variables deliver the arguments, and exit codes carry success or failure back to whoever ran the script, which is also the key to finding out why a script went wrong.
Variables the shell fills in for you
Besides the variables you create, as in "Dot files, environment variables, and the command path", the shell maintains a set of special parameters. They hold the script's arguments, its name, its process ID and the result of the last command. You read them with a dollar sign, like other variables, but you cannot assign to them with =; the shell sets them itself. When a line full of these symbols looks like noise, take it apart one symbol at a time.
Positional parameters and shift
$1, $2 and so on hold the arguments in order; from the tenth on you need braces, ${10}, because $10 means $1 followed by a 0. The built-in shift discards $1 and moves every other argument down one place. A script args.sh that prints its first and third arguments, then shifts, gives this for ./args.sh red green "light blue": First: red, Third: light blue, then After shift, first: green, count: 2. The quotes made light blue a single argument. Run with no arguments, shift has nothing to remove: in bash it fails quietly with status 1, and $1 is simply empty.
Count, name and process ID
$# is the number of arguments, 3 in the run above, falling as shift removes them; when it reaches 0, nothing is left. $0 is the name the script was started with: ./args.sh when run that way, need.sh when run as sh need.sh. Use it in messages so users know which program complained, and send those messages to standard error with >&2 so they do not mix with real output. $$ is the process ID of the shell running the script, different on every run; "Temporary files and here documents" explains why it is a weak way to make unique filenames.
All the arguments: "$@" and "$*"
To pass every argument on to another command, use "$@" in double quotes: it expands to each argument as a separate, intact word. Unquoted $@ undergoes word splitting, and "$*" joins everything into one word. Called with the two arguments "a b" and c, printf '<%s>' prints three different results: unquoted $@ gives <a><b><c>, "$@" gives <a b><c>, and "$*" gives <a b c>. Only "$@" reproduces exactly what the caller typed, so a wrapper script that adds options to another command should end its command line with "$@".
Exit codes and $?
Every program that finishes leaves a number, its exit code (also called exit status), for the process that started it. Zero means success; anything from 1 to 255 normally means a problem. $? holds the code of the last command. After ls / > /dev/null, echo $? prints 0. After ls /no/such/dir, GNU ls reports cannot access and echo $? prints 2, which its manual defines as serious trouble. Read $? immediately, or save it with rc=$?, because the next command replaces it: a second echo $? prints 0, the status of the first echo. A script sets its own code with exit, such as exit 0 or exit 1.
When non-zero is not an error
Some programs use exit codes for answers, not just for errors. grep returns 0 when a line matches, 1 when none does and 2 for a real error, such as a missing file. diff returns 0 when files are identical, 1 when they differ and 2 for trouble. The shell itself reserves a few values: 127 means command not found, 126 means found but not executable, and 128 + n means killed by signal n. A sleep stopped by kill, which sends SIGTERM (signal 15), leaves status 143. The EXIT STATUS section of a manual page lists a program's codes.
Worked example: refusing bad arguments
A script need.sh must be given exactly one filename. 1. Test the count first: if [ $# -ne 1 ]; then, followed by an error line and exit 2, then fi. (The test command is taught in "Conditionals".) 2. Write the error to standard error with the script's name: echo "$0: expected 1 argument, got $#" >&2. 3. Run sh need.sh with nothing: it prints need.sh: expected 1 argument, got 0, and echo $? prints 2. 4. Run sh need.sh a b 2>/dev/null: the message is hidden, but the status is still 2, so a calling script can react. 5. Run sh need.sh report.txt: it prints Processing report.txt with status 0. A distinct code for usage errors lets callers tell them apart from other failures.
Worked example: tracing with set -x
This script misbehaves: name="report 1.txt", then touch $name, then ls "$name". 1. Add set -x after the shebang, or run bash -x script. Each command is printed after expansion, prefixed with +. 2. The trace shows + name='report 1.txt', then + touch report 1.txt. 3. That line shows two words, so touch created two files, report and 1.txt. 4. The ls line confirms it: ls: cannot access 'report 1.txt': No such file or directory. 5. Fix it by quoting: touch "$name". The trace exposes word splitting that the script's own text hides. Turn tracing off again with set +x.
set -e, set -u and pipefail
set -e makes a script exit as soon as a command fails. A script that runs echo start, then ls /no/such/dir, prints start and the ls error and stops with status 2. The bash manual lists exceptions: a failure does not stop the script inside an if or while test, in any part of a && or || list except the last, or in any pipeline stage but the last. set -u turns an unset variable into an error: a typo such as $nmae gives nmae: unbound variable and status 1. A pipeline's status is normally that of its last command, so grep zzz file | sort reports 0 even when grep finds nothing; after set -o pipefail the same pipeline reports 1.
ShellCheck
ShellCheck is a free, open-source static analyser for shell scripts: it reads a script without running it and points out likely bugs. Install it with sudo apt install shellcheck on Debian and Ubuntu or sudo dnf install ShellCheck on Fedora, then run shellcheck script.sh. Each warning has a code with a wiki page; the unquoted touch $name above would draw SC2086, "Double quote to prevent globbing and word splitting." Running it on every script catches most of the quoting mistakes from "Script basics, quoting, and literals".
Common mistakes to avoid
First, writing $10 for the tenth argument instead of ${10}. Second, passing arguments on with unquoted $@ or with "$*" instead of "$@". Third, checking $? after another command, even an echo, has replaced it. Fourth, treating every non-zero status as failure: grep's 1 means no match. Fifth, sending error messages to standard output, where they mix with data. Sixth, assuming set -e catches every failure; it ignores failures in if tests, in && and || lists and in early pipeline stages.
Key takeaways
$1, $2 up to ${10} and beyond are the arguments; shift moves them down; $# counts them; "$@" passes them on intact; $0 is the script's name and $$ its process ID. Every command leaves an exit code in $?: 0 for success, non-zero otherwise, with exceptions such as grep and diff using 1 for a normal answer. 127 means command not found and 128 + n means killed by signal n. End scripts with a meaningful exit code. Debug with set -x, harden with set -e, set -u and set -o pipefail, and check scripts with ShellCheck.
Flashcards
Flashcard
The script's arguments in order
Test your understanding
Question 1 of 5
A script runs printf '<%s>' "$@" and is called with the two arguments "a b" and c. What does it print?
Question 2 of 5
You run grep -q error app.log and no line contains error. What is the exit status, and what does it mean?
Question 3 of 5
A script runs ls /missing, then echo $?, then echo $? again. On a GNU system, what do the two echo commands print?
Question 4 of 5
A long-running job is stopped with kill, which sends SIGTERM (signal 15). What exit status does the shell report for it?
Question 5 of 5
A script has set -e and runs grep zzz file | sort, where grep finds nothing. Why does the script keep going?
