Skip to main content
Bash and Linux

Arguments and Exit Codes

easyBash scripts and automation

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

TEXT
line 1
line 2
line 3
  1. Run it with no arguments.
  2. Run it with a missing file.
  3. Run it with a count that is not a number.
  4. Run it correctly, so it prints the first 2 lines.
  5. Show the difference between "$@" and $*.

For each run, print the command, everything it printed, and its exit code.

Expected output:

Bash
$ show-head.sh
usage: show-head.sh FILE COUNT (print the first COUNT lines of FILE)
-> exit 2
$ show-head.sh nofile.txt 2
error: no such file: nofile.txt
-> exit 1
$ show-head.sh data.txt abc
error: COUNT must be a whole number, got: abc
-> exit 2
$ show-head.sh data.txt 2
line 1
line 2
-> exit 0
== "$@" keeps arguments whole, $* splits them ==
with "$@": [two words] [one]
with $*: [two] [words] [one]

Hints

Hint 1: $# 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:

%%{init: {"flowchart": {"padding": 18, "nodeSpacing": 30, "rankSpacing": 40, "htmlLabels": true}, "themeVariables": {"fontSize": "18px"}}}%% flowchart TB A["#!/usr/bin/env bash"]:::gray --> B["set -euo pipefail"]:::purple B --> C["usage()"]:::blue C --> D{{"arguments OK?"}}:::yellow D --> E["do the work, exit 0"]:::green D --> F["usage to stderr, exit 2"]:::red 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
  1. #!/usr/bin/env bash on line 1, so it runs with bash.
  2. set -euo pipefail.
  3. A usage function.
  4. Checks: right number of arguments, files exist, values look right.
  5. 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:

%%{init: {"flowchart": {"padding": 18, "nodeSpacing": 30, "rankSpacing": 40, "htmlLabels": true}, "themeVariables": {"fontSize": "18px"}}}%% flowchart LR subgraph CODES["exit codes"] direction TB C0["0
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.

  1. try prints the command, runs the tool with 2>&1 so its errors show in the output, and prints the exit code.
  2. No arguments: usage, exit 2. Missing file: error, exit 1. Bad count: error, exit 2. Correct call: two lines, exit 0.
  3. 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" one

Interview follow-ups

  • Accept an optional third argument, an output file, defaulting to stdout.

    Allow two or three arguments: [[ $# -eq 2 || $# -eq 3 ]] || usage, then out=${3:--}, where - means stdout. At the end, write with if [[ $out == - ]]; then head -n "$count" -- "$file"; else head -n "$count" -- "$file" > "$out"; fi. Update the usage line to show the option in brackets, like FILE 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.