Check Exit Codes in Bash: 9 Proven Ways to Avoid Errors

You can check exit codes in Bash in one line, yet scripts still report success after a failed step. The usual reason is that the number was read too late, or something replaced it. Every example here ran on Debian 13 with Bash 5.2.37 in a clean container. Each block shows the script, then what it printed; the last line in brackets is the status of the whole script.

If you want the table of reserved values and the Python side, read the earlier guide on exit codes in shell and Python scripts. This one is about the checking itself.

1. Read exit codes in Bash with $?

The special parameter $? holds the status of the last command. Zero means success. Anything from 1 to 255 means something else happened, and each program chooses its own meaning. ls used 2 for a missing file:

$ cat s.sh
ls names.txt
echo "status: $?"
ls missing.txt
echo "status: $?"
$ bash s.sh
names.txt
status: 0
ls: cannot access 'missing.txt': No such file or directory
status: 2
[exit 0]

Each exit code lives for one command only. In the next run, the first echo succeeded, so the second read shows 0:

$ cat s.sh
false
echo "first read: $?"
echo "second read: $?"
$ bash s.sh
first read: 1
second read: 0
[exit 0]

An if statement overwrites it too. When no branch runs, the whole if returns 0, even though grep found nothing:

$ cat s.sh
grep -q gamma names.txt
if [ $? -eq 0 ]; then echo found; fi
echo "after if: $?"
$ bash s.sh
after if: 0
[exit 0]

2. Save the status before doing anything else

Copy $? into a variable on the very next line. A log message between the command and the check is enough to lose it:

$ cat s.sh
grep -q gamma names.txt
rc=$?
echo "log: grep finished"
echo "rc=$rc  but \$? is now $?"
$ bash s.sh
log: grep finished
rc=1  but $? is now 0
[exit 0]

3. Test the command, or branch on each exit code

When success or failure is all you need, put the command inside the condition: if grep -q alpha names.txt; then .... When the values differ in meaning, use case. grep has three outcomes, and a plain if treats a typo in a file name the same as "no match":

$ cat s.sh
for f in names.txt:alpha names.txt:gamma nofile:alpha; do
  grep -q "${f#*:}" "${f%:*}" 2>/dev/null; echo "grep ${f#*:} ${f%:*} -> $?"
done
$ bash s.sh
grep alpha names.txt -> 0
grep gamma names.txt -> 1
grep alpha nofile -> 2
[exit 0]
$ cat s.sh
rc=0
grep -q alpha nofile || rc=$?
case $rc in
  0) echo "match" ;;
  1) echo "no match" ;;
  *) echo "grep failed with $rc"; exit "$rc" ;;
esac
$ bash s.sh
grep: nofile: No such file or directory
grep failed with 2
[exit 2]

The rc=0; command || rc=$? form is worth memorising. It keeps the exit code and works with or without set -e.

4. Recognise 126, 127, 124 and signals

$ cat s.sh
nosuchcommand
echo "not found: $?"
touch t.sh; chmod -x t.sh; ./t.sh
echo "not executable: $?"
bash -c "kill -TERM \$\$"
echo "SIGTERM: $?"
timeout 1 sleep 5
echo "timeout: $?"
bash -c "exit 256"; echo "exit 256: $?"
bash -c "exit -1"; echo "exit -1: $?"
bash -c "exit abc"; echo "exit abc: $?"
$ bash s.sh
s.sh: line 1: nosuchcommand: command not found
not found: 127
s.sh: line 3: ./t.sh: Permission denied
not executable: 126
Terminated
SIGTERM: 143
timeout: 124
exit 256: 0
exit -1: 255
bash: line 1: exit: abc: numeric argument required
exit abc: 2
[exit 0]

127 means Bash could not find the command and 126 means it found the file but could not execute it. timeout returns 124 when it stops a command. A process killed by a signal reports 128 plus the signal number, so SIGTERM shows as 143. An exit code wraps at 256, which is why exit 256 looked like success. Never use a count of errors as the exit value.

kill -l turns the number back into a name:

$ cat s.sh
timeout 1 sleep 5; rc=$?
if (( rc > 128 )); then echo "signal $(kill -l $((rc-128)))"; else echo "code $rc"; fi
bash -c "kill -KILL \$\$"; rc=$?
if (( rc > 128 )); then echo "signal $(kill -l $((rc-128)))"; else echo "code $rc"; fi
$ bash s.sh
code 124
s.sh: line 3:  3059 Killed                  bash -c "kill -KILL \$\$"
signal KILL
[exit 0]

Tools define their own exit code tables. curl gave 7 for a refused connection and 6 for a name that does not resolve. An HTTP 404 still exits 0 unless you add -f:

$ cat s.sh
curl -s -o /dev/null http://127.0.0.1:1/ ; echo "refused: $?"
curl -s -o /dev/null http://no-such-host.invalid/ ; echo "dns: $?"
curl -s -o /dev/null https://deb.debian.org/no-such-page ; echo "404 without -f: $?"
curl -sf -o /dev/null https://deb.debian.org/no-such-page ; echo "404 with -f: $?"
$ bash s.sh
refused: 7
dns: 6
404 without -f: 0
404 with -f: 22
[exit 0]

5. Check exit codes in pipelines

By default a pipeline returns the exit code of its last command. Here cat failed and the pipeline still reported 0:

$ cat s.sh
cat nofile | wc -l
echo "pipeline: $?"
echo "PIPESTATUS: ${PIPESTATUS[*]}"
$ bash s.sh
cat: nofile: No such file or directory
0
pipeline: 0
PIPESTATUS: 0
[exit 0]

Look closely at the last line. PIPESTATUS shows a single 0 because the echo before it had already replaced the array. Read it immediately, and only once:

$ cat s.sh
cat nofile 2>/dev/null | wc -l >/dev/null
echo "A: ${PIPESTATUS[*]}"
echo "B: ${PIPESTATUS[*]}"
$ bash s.sh
A: 1 0
B: 0
[exit 0]

set -o pipefail makes the pipeline fail when any part fails. It also reports harmless early exits: head closed the pipe and yes ended with 141, which is 128 plus SIGPIPE.

$ cat s.sh
set -o pipefail
cat nofile 2>/dev/null | wc -l
echo "pipefail: $?"
yes | head -n 1
echo "yes|head: $? (${PIPESTATUS[*]})"
$ bash s.sh
0
pipefail: 1
y
yes|head: 141 (141 0)
[exit 0]

6. Watch for local, export and bare return

$ cat s.sh
f() { local out=$(cat nofile 2>/dev/null); echo "local: $?"; }
g() { local out; out=$(cat nofile 2>/dev/null); echo "split: $?"; }
f; g
export V=$(false); echo "export: $?"
V=$(false); echo "plain: $?"
$ bash s.sh
local: 0
split: 1
export: 0
plain: 1
[exit 0]
Checking exit codes in Bash: local and export hide a failed command substitution
The same failed command, four ways to assign its output.

local and export are commands with their own status, and it replaces the status of the substitution. Declare first, assign on a second line. Functions follow a similar rule: they return the status of the last command that ran, unless you say otherwise.

$ cat s.sh
f() { false; echo "last command"; }
f; echo "function status: $?"
g() { false; return; }
g; echo "bare return: $?"
$ bash s.sh
last command
function status: 0
bare return: 1
[exit 0]

7. Negation and chains that mislead

$ cat s.sh
! false; echo "! false -> $?"
if ! grep -q gamma names.txt; then echo "inside: $?"; fi
true && false || echo "fallback ran although the test was true"
$ bash s.sh
! false -> 0
inside: 0
fallback ran although the test was true
[exit 0]

Inside if ! command, $? is the status of the negated test, so the real exit code is gone. The line a && b || c is also not an if/else: c runs whenever b fails. Compare the two ways of keeping a value:

$ cat s.sh
if ! cp nofile copy 2>/dev/null; then rc=$?; echo "rc=$rc"; fi
rc=0; cp nofile copy 2>/dev/null || rc=$?; echo "rc=$rc"
$ bash s.sh
rc=0
rc=1
[exit 0]

8. Exit codes in Bash with set -e

With set -e the shell stops at the first unhandled failure. A later rc=$? line is never reached, and the script gives no message at all:

$ cat s.sh
set -e
grep -q gamma names.txt
rc=$?
echo "never printed"
$ bash s.sh
[exit 1]
$ cat s.sh
set -e
rc=0; grep -q gamma names.txt || rc=$?
echo "kept rc=$rc and still running"
$ bash s.sh
kept rc=1 and still running
[exit 0]

The set builtin section of the Bash manual lists the places where set -e is ignored, including conditions and every part of an && or || list except the last. Read that list before relying on it.

9. Collect results from background jobs

$ cat s.sh
(sleep 1; exit 7) & p1=$!
(exit 0) & p2=$!
wait "$p1"; echo "job1: $?"
wait "$p2"; echo "job2: $?"
(exit 5) & wait; echo "bare wait: $?"
$ bash s.sh
job1: 7
job2: 0
bare wait: 0
[exit 0]

wait with a process ID returns that job's status. Without arguments it waited for the job and returned 0, although the job exited with 5. Keep each PID if the result matters.

Give your own script clear exit codes

Callers can only react to what you return. Use a different number per cause, send messages to standard error, and note the values in the header or the usage text:

$ cat check.sh
#!/usr/bin/env bash
set -u
[ "$#" -eq 1 ] || { echo "usage: $0 FILE" >&2; exit 2; }
[ -r "$1" ]    || { echo "cannot read $1" >&2; exit 3; }
grep -q alpha "$1" || { echo "alpha missing in $1" >&2; exit 1; }
echo "ok"
$ bash check.sh 
usage: check.sh FILE
[exit 2]
$ bash check.sh nofile
cannot read nofile
[exit 3]
$ bash check.sh names.txt
ok
[exit 0]

A cron job, a CI step or a parent script can now tell a wrong call (2) from an unreadable file (3) and a failed check (1). The reference for the reserved values is the Exit Status page of the GNU Bash manual.

Quick checklist for exit codes in Bash

  • Save $? on the next line, or test the command directly.
  • Check the manual of each tool before treating every non-zero value as an error.
  • Use pipefail, and expect 141 from commands cut short by head.
  • Split local and the assignment.
  • Wait for each background PID on its own.

When a script misbehaves, add echo "rc=$?" directly after the suspect line and run it with bash -x. Most wrong exit codes in Bash turn out to be a command you did not notice running in between.

Comments

Popular posts from this blog

Linux Desktop Frozen? 5 Proven Fixes Before a Hard Reboot

Minecraft Bedrock on Linux: 4 Proven Ways to Play in 2026

DXVK in Wine on Linux: 7 Easy Setup Steps, Tested