Arguments and Exit Codes
Problem statement
Write a script that needs a file name and a count, prints a usage message to stderr and exits with code 2 when the arguments are missing or wrong, and only then does its work. Every script someone else will run needs this: a clear message beats a cryptic error from deep inside the script.
The script saves the tool as show-head.sh, a data file, and then runs the tool several ways:
data.txt
line 1line 2line 3- Run it with no arguments.
- Run it with a missing file.
- Run it with a count that is not a number.
- Run it correctly, so it prints the first 2 lines.
- Show the difference between
"$@"and$*.
For each run, print the command, everything it printed, and its exit code.
Expected output:
$ show-head.shusage: show-head.sh FILE COUNT (print the first COUNT lines of FILE) -> exit 2$ show-head.sh nofile.txt 2error: no such file: nofile.txt -> exit 1$ show-head.sh data.txt abcerror: COUNT must be a whole number, got: abc -> exit 2$ show-head.sh data.txt 2line 1line 2 -> exit 0== "$@" keeps arguments whole, $* splits them ==with "$@": [two words] [one]with $*: [two] [words] [one]Hints
$# is the number of arguments and $1, $2 are the first two. [[ $# -eq 2 ]] || usage calls a usage function when the count is wrong.Approach
Optimal: Usage, checks, then work
Covers: the shebang, $0, $1, $#, "$@" vs $*, shift, a usage function, >&2, exit codes 0, 1 and 2, =~ regex checks, the shape of a good script.
Strict mode, used on every page in this section. The second line, set -euo pipefail, makes bash stop on mistakes instead of carrying on:
| Option | Means |
|---|---|
-e |
exit as soon as a command fails (with some exceptions, see Handle Command Failures) |
-u |
treat an unset variable as an error, instead of silently using empty text |
-o pipefail |
a pipeline fails if any command in it fails, not just the last one |
Put it right after the shebang line #!/usr/bin/env bash in every script you write.
The shape of a good script. Almost every well-behaved script follows the same order:
#!/usr/bin/env bashon line 1, so it runs with bash.set -euo pipefail.- A
usagefunction. - Checks: right number of arguments, files exist, values look right.
- Only then, the real work.
Checking everything first means the script never stops halfway through, having done half a job.
Arguments.
| Name | Means |
|---|---|
$0 |
how the script was called (${0##*/} gives just the name) |
$1, $2 ... |
the arguments, in order |
$# |
how many there are |
"$@" |
all of them, each as its own word |
shift |
drop $1 and move the rest down by one |
"$@" vs $*. "$@" passes every argument exactly as given, so "a b" stays one argument. $* (unquoted) joins and re-splits them, so "a b" becomes two. Pass arguments on with "$@", always.
Errors to stderr, with the right exit code. Normal output goes to stdout; messages about problems go to stderr with >&2, so ./show-head.sh data.txt 2 > out.txt saves only the real output and still shows errors on screen. The exit code tells other scripts and CI what happened:
worked"]:::green ~~~ C1["1
failed at runtime"]:::red ~~~ C2["2
called wrongly"]:::yellow end classDef blue fill:#dbeafe,stroke:#2563eb,color:#1e3a8a,stroke-width:2px classDef yellow fill:#fef3c7,stroke:#d97706,color:#78350f,stroke-width:2px classDef green fill:#d1fae5,stroke:#059669,color:#064e3b,stroke-width:2px classDef red fill:#fee2e2,stroke:#dc2626,color:#7f1d1d,stroke-width:2px classDef purple fill:#ede9fe,stroke:#7c3aed,color:#4c1d95,stroke-width:2px classDef gray fill:#f3f4f6,stroke:#6b7280,color:#111827,stroke-width:2px linkStyle default stroke:#94a3b8,stroke-width:2px style CODES fill:transparent,stroke:#6b7280,stroke-width:2px
| Code | Use for |
|---|---|
| 0 | it worked |
| 1 | it failed at runtime (missing file, network error) |
| 2 | it was called wrongly (missing or bad arguments) |
Checking values. [[ -f $file ]] checks the file exists. [[ $count =~ ^[0-9]+$ ]] checks the text against a regular expression: start, one or more digits, end. Without it, head -n abc would fail later with a less helpful message.
Walking through the code. The # Setup: lines write the tool to show-head.sh and create data.txt, so skip past the setup part; the tool itself is the solution.
tryprints the command, runs the tool with2>&1so its errors show in the output, and prints the exit code.- No arguments: usage, exit 2. Missing file: error, exit 1. Bad count: error, exit 2. Correct call: two lines, exit 0.
- The last part prints each argument in brackets with
"$@"and with$*.
Edge cases. A script saved with Windows line endings fails with bad interpreter: /usr/bin/env: 'bash\r'; fix it with sed -i 's/\r$//'. Arguments can start with -, so pass them on after -- when calling tools like rm or grep.
#!/usr/bin/env bash
set -euo pipefail
# Setup: write the tool and a data file in a fresh temporary folder
cd "$(mktemp -d)"
printf 'line 1\nline 2\nline 3\n' > data.txt
cat > show-head.sh << 'TOOL'
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "usage: ${0##*/} FILE COUNT (print the first COUNT lines of FILE)" >&2
exit 2
}
[[ $# -eq 2 ]] || usage
file=$1
count=$2
if [[ ! -f $file ]]; then
echo "error: no such file: $file" >&2
exit 1
fi
if [[ ! $count =~ ^[0-9]+$ ]]; then
echo "error: COUNT must be a whole number, got: $count" >&2
exit 2
fi
head -n "$count" -- "$file"
TOOL
try() {
echo "\$ show-head.sh${*:+ $*}"
bash ./show-head.sh "$@" 2>&1 && echo " -> exit 0" || echo " -> exit $?"
}
try
try nofile.txt 2
try data.txt abc
try data.txt 2
echo "== \"\$@\" keeps arguments whole, \$* splits them =="
show() { local out; out=$(printf '[%s] ' "$@"); echo "${out% }"; }
args() { echo -n 'with "$@": '; show "$@"; echo -n 'with $*: '; show $*; }
args "two words" oneInterview follow-ups
Accept an optional third argument, an output file, defaulting to stdout.
Allow two or three arguments:
[[ $# -eq 2 || $# -eq 3 ]] || usage, thenout=${3:--}, where-means stdout. At the end, write withif [[ $out == - ]]; then head -n "$count" -- "$file"; else head -n "$count" -- "$file" > "$out"; fi. Update the usage line to show the option in brackets, likeFILE COUNT [OUTPUT], which is the usual way to mark an optional argument.
Frequently asked questions
Because people and tools treat the two streams differently. When output is piped or saved, ./script > result.txt, stdout goes to the file but stderr still reaches the screen, so errors are seen instead of hidden inside the data. Other scripts can also capture the output with $(...) without getting error text mixed in. Combined with a non-zero exit code, it makes your script behave like any standard Linux tool.
The file has Windows line endings (\r\n), usually because it was edited on Windows or copied through a tool that converted it. The kernel reads the shebang as bash\r, which does not exist, and bash sees \r at the end of every command. Run file script.sh to confirm ("with CRLF line terminators"), then fix it with sed -i 's/\r$//' script.sh or dos2unix. Setting .gitattributes to keep *.sh as LF stops it happening again.
It is a kind habit and costs two lines: [[ ${1:-} == -h || ${1:-} == --help ]] && { usage_text; exit 0; }. Note that help asked for on purpose should go to stdout and exit 0, while usage shown because of a mistake goes to stderr and exits 2. Include what the script does, its arguments, an example, and any environment variables it reads. Future you is the most common reader.