Linux Labs

Bash: text processing and scripts / Stage 5 of 9

Arguments, quotes and file checks

Not running Starting usually ~20 s
Leave the lesson

Step 4 of 7 · theory · 5 min

The exit status and the usage line

A script answers with more than text. The number it finishes with tells the caller whether it worked.

Every program, when it finishes, hands back a number — its exit status: 0 means it worked, any other number means it did not. bash keeps the last command's code in $?, and echo $? right after the command prints it. wc -l in the previous step exited with code 1: it could not read one of the three files.

A script sets its own code with exit N: it ends the script at once with code N. What each code means is the script author's contract. In this lesson: 0 — done, 1 — something is wrong with the file, 2 — the script was called the wrong way. Without exit, a script's code is the code of its last command.

A wrong call is, for instance, one with no arguments, when $# is 0. Numbers are compared with the -eq test: [ $# -eq 0 ]. The line that tells how to call the script goes to the error stream: >&2 after echo sends the output to stream 2, where programs write their errors. That way the usage line does not end up in the file the script's result was redirected to.

bash
if [ $# -eq 0 ]; then
    echo "Usage: count.sh DIR" >&2
    exit 2
fi
Check yourself 1 question

With no arguments, the script runs echo "Usage: save.sh FILE" >&2 and exit 2. You run ./save.sh > out.txt. What ends up in out.txt?

  • > redirects stream 1, and the usage line went to stream 2 through >&2 — to the screen. wc -c out.txt prints 0.

  • The exit status is not printed to stdout: $? holds it. out.txt is empty — wc -c out.txt prints 0.

  • The shell creates out.txt before the script even starts, as in the lesson on output streams. ls -l out.txt shows an empty file.

The shell created out.txt before the script started, and > sent only stream 1 there. The usage line went to stream 2 and stayed on the screen, and echo $? after the run prints 2.

Key points

  • The exit status is the script's answer to its caller: exit N sets it, and echo $? right after the run shows it.
  • A usage line for a wrong call goes to the error stream through >&2, and the script exits with a non-zero code.
Ubuntu 24.04
Loading…