Exit status and && / || lists

Beginner · 15 min

Every command ends with a number, 0 for success. Read it with $?, chain commands on it with && and ||, and avoid the A && B || C trap.

Before thisstdin, stdout and stderrYour first script - shebang and execute bit

Luke Smith · 15 min

Exit status and && / || lists

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Luke SmithReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • Every command finishes with an exit status from 0 to 255. Zero means success and anything else means failure, and `$?` holds the status of the last command.
  • `A && B` runs B only if A succeeded. `A || B` runs B only if A failed. `A; B` runs B regardless.
  • `A && B || C` is not an if/else. If A succeeds and B fails, C runs too.
  • `!` negates a status, and `exit N` ends a script with status N. A script's own status is that of its last command unless you set it.
  • Command-not-found is 127, a non-executable file is 126, and `grep` uses 1 for no match but 2 for a real error, so read each tool's documentation.

Programs answer with a number

When a command finishes, it leaves behind a small integer: its exit status. By convention, 0 means “it worked” and anything from 1 to 255 means “it didn’t”, with the number often hinting at why. Your shell keeps the most recent one in $?.

This is how a shell can make decisions at all. There is no boolean type. The “true” and “false” a script cares about are simply status 0 and non-zero. Notice the inversion if you come from other languages: zero is success, because there is one way to succeed and many ways to fail.

$ true; echo "true -> $?"; false; echo "false -> $?"
true -> 0
false -> 1
$ ls nope; echo "ls nope -> $?"
ls: nope: No such file or directory
ls nope -> 1

That ls status is from macOS’s BSD ls. I only ran it on a Mac; the GNU ls on Linux is documented to return 2 for a missing file, so don’t hard-code the number, test for non-zero.

Statuses are tool-specific

$ grep -q ' 500 ' logs/access.log; echo "match -> $?"
match -> 0
$ grep -q ' 999 ' logs/access.log; echo "no match -> $?"
no match -> 1
$ grep -q ' 500 ' no-such-file; echo "error -> $?"
grep: no-such-file: No such file or directory
error -> 2
$ nosuchcmd; echo "not found -> $?"
bash: nosuchcmd: command not found
not found -> 127

For grep, “no match” is 1 but a real error is 2, so a script that treats “non-zero” as “pattern not present” will quietly misread a typo in a filename as a clean result. Bash itself uses 127 for command not found (seen above) and 126 for a file that isn’t executable (from the manual, not run here). Exit statuses wrap at 256, so (exit 300) gave 44.

Chaining on success and failure

Using $? after every command gets old. The shell offers operators that look at the status for you:

  • A && B runs B only if A exited 0.
  • A || B runs B only if A exited non-zero.
  • A; B runs B either way.

A guard in front of something risky is the classic use. The next command failed to change directory, and the && kept the echo from running while the shell stayed where it was:

$ cd /nonexistent && echo "inside"; echo "still here: $PWD"
bash: cd: /nonexistent: No such file or directory
still here: /work/l28/out

Combined, they let you branch:

$ grep -q ' 404 ' ../logs/access.log && echo "some 404s" || echo "no 404s"
some 404s
$ grep -q ' 999 ' ../logs/access.log && echo "some 999s" || echo "no 999s"
no 999s

! flips a status, so ! grep -q ' 999 ' file && echo ... runs the echo when the pattern is absent. A list like this is evaluated left to right, and the status of the whole list is that of the last command that ran.

The A && B || C trap

It is tempting to read A && B || C as “if A then B else C”. It isn’t, because || looks at the status of whatever ran last, not of A:

$ true && false || echo "C ran even though A succeeded"
C ran even though A succeeded

A succeeded, B failed, so C ran as well. Use that form only when B can’t fail, such as an echo. For anything else, use a real if, covered in the conditionals lesson.

Your script’s own status

A script exits with the status of its last command unless it says otherwise, and exit N says otherwise. Here is logsum version 2, which refuses to run on an unreadable file and reports through its exit status:

#!/usr/bin/env bash
# logsum v2: exits non-zero when it cannot do its job
log=${1:-logs/access.log}
[[ -r $log ]] || { echo "logsum: cannot read $log" >&2; exit 2; }
total=$(wc -l < "$log")
errors=$(awk '$8 >= 500' "$log" | wc -l)
echo "requests: $((total)) server errors: $((errors))"
(( errors == 0 ))

The || branch prints to standard error and exits 2. The last line is a test, so the script’s status is 0 only when there are no server errors, which makes it usable as a health check. ShellCheck found nothing to report.

$ ./logsum nosuch.log; echo "status: $?"
logsum: cannot read nosuch.log
status: 2
$ ./logsum; echo "status: $?"
requests: 200 server errors: 24
status: 1

Functions return a status with return N (f -> 5 in my test). A pipeline’s status is its last stage, so false | true reported 0. The strict-mode lesson shows how to change that.

About the video

Luke Smith’s “Never say ‘If’ writing a Bash script! (Exit codes & logical operators)” is 14 minutes 50 seconds and was published in March 2020. I had no transcript. The description argues that most if statements in shell scripts can be replaced by && and ||, which matches the title. That is an opinion, not a rule, and the trap above is the reason to hold it loosely. It is in English. I chose it for being the clearest take on &&/|| I found, and You Suck at Programming’s exit-code video is linked for the gotchas.

Where this fits

You can now run commands conditionally and report your own result. For anything longer than one condition, the next lesson covers a proper if statement with test and [[ ]].

Check yourself

  1. 01What does `mkdir build && cd build` do if `mkdir` fails?

    It skips `cd`. The `&&` runs the right side only when the left side exits 0, so you don't end up inside the wrong directory.

  2. 02Why is `cmd1 && cmd2 || cmd3` not the same as if/then/else?

    If `cmd1` succeeds but `cmd2` fails, the `||` still fires and runs `cmd3`. I saw `true && false || echo ...` print its message even though the first command succeeded.

  3. 03`grep -q pattern file` returns 1. Is that an error?

    No, 1 means no line matched. Status 2 means a real error such as a missing file. Scripts that treat any non-zero as 'pattern absent' hide typos in file names.

  4. 04What exit status does a pipeline like `false | true` report?

    The status of its last command, so 0 here. The failure of an earlier stage is hidden unless you use `set -o pipefail`, covered in the strict-mode lesson.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark