ZetCode

Linux Exit Codes and Bash Strict Mode

last modified October 23, 2026

Every command on Linux finishes with an exit code, also called exit status or return code: a number from 0 to 255. Zero means success, any other value failure. The shell uses exit codes to decide what to do next in conditions, && and || lists, and loops, and scripts use them to report errors to their callers.

This article shows how to read exit codes, what the common values mean, and how to write Bash scripts that stop on errors with the so-called strict mode, set -euo pipefail, including its pitfalls. The examples were run with Bash 5.2 on Debian 12.

The $? variable

The special parameter $? holds the exit code of the last command.

true; echo $?
false; echo $?
ls /etc/hostname; echo $?
ls /nonexistent; echo $?

true and false do nothing but return 0 and 1. ls returns 2 for a file that does not exist. Error messages and exit codes are independent: a program prints a message to standard error and sets an exit code; scripts should check the code, not parse the message.

$ true; echo $?
0
$ false; echo $?
1
$ ls /etc/hostname; echo $?
/etc/hostname
0
$ ls /nonexistent; echo $?
ls: cannot access '/nonexistent': No such file or directory
2

Exit codes with a meaning

Some commands use different non-zero codes for different outcomes. The grep command is the best-known example.

grep -q jano /etc/passwd; echo $?
grep -q nosuchuser /etc/passwd; echo $?
grep -q jano /nonexistent; echo $?

grep returns 0 when it finds a match, 1 when it finds none, and 2 on an error. Not finding anything is a normal result, not an error, and scripts can tell the two apart. diff and cmp follow the same convention: 0 for equal files, 1 for different, 2 for trouble. The manual page of a command lists its exit codes, usually in an EXIT STATUS section.

$ grep -q jano /etc/passwd; echo $?
0
$ grep -q nosuchuser /etc/passwd; echo $?
1
$ grep -q jano /nonexistent; echo $?
grep: /nonexistent: No such file or directory
2

$? is overwritten by every command

$? changes after every command, including echo.

ls /nonexistent 2> /dev/null; echo "status: $?"; echo "status: $?"
ls /nonexistent 2> /dev/null; rc=$?; echo "saved: $rc"; echo "still: $rc"

The second echo prints the status of the first echo, which succeeded. To use the status more than once, save it in a variable right after the command.

$ ls /nonexistent 2> /dev/null; echo "status: $?"; echo "status: $?"
status: 2
status: 0
$ ls /nonexistent 2> /dev/null; rc=$?; echo "saved: $rc"; echo "still: $rc"
saved: 2
still: 2

Special exit codes

The shell itself sets some values, and processes killed by a signal get 128 plus the signal number. The commands were typed in an interactive shell.

nosuchcmd; echo $?
ls -l notexec.sh
./notexec.sh; echo $?
timeout 1 sleep 5; echo $?
sleep 30 &
kill $!; wait $!; echo $?
sleep 30 &
kill -9 $!; wait $!; echo $?
kill -l 15 9

127 means that the command was not found, and 126 that it was found but could not be executed, here because the file lacks the execute permission. timeout returns 124 when it had to stop the command. A process terminated by SIGTERM (15) has the status 128 + 15 = 143, and one killed by SIGKILL (9) 137. kill -l translates signal numbers to names. A status of 137 in a container log often means that the kernel killed the process for using too much memory.

$ nosuchcmd; echo $?
bash: nosuchcmd: command not found
127
$ ls -l notexec.sh
-rw-rw-r-- 1 jano jano 23 Oct 23 21:53 notexec.sh
$ ./notexec.sh; echo $?
bash: ./notexec.sh: Permission denied
126
$ timeout 1 sleep 5; echo $?
124
$ sleep 30 &
[1] 52
$ kill $!; wait $!; echo $?
[1]+  Terminated              sleep 30
143
$ sleep 30 &
[1] 55
$ kill -9 $!; wait $!; echo $?
[1]+  Killed                  sleep 30
137
$ kill -l 15 9
TERM
KILL

Ctrl+C

Pressing Ctrl+C sends SIGINT, signal 2.

sleep 30
echo $?

The status 130 is 128 + 2. Scripts that call other programs can check for it to stop when the user interrupts them.

$ sleep 30
^C
$ echo $?
130

Exit codes of scripts

The exit builtin ends a script with a given code. Without exit, a script returns the status of its last command.

bash -c 'exit 3'; echo $?
bash -c 'exit 255'; echo $?
bash -c 'exit 256'; echo $?
bash -c 'exit 300'; echo $?
bash -c 'exit -1'; echo $?
cat last.sh
bash last.sh; echo $?

Only the lowest eight bits are kept, so 256 becomes 0, 300 becomes 44, and -1 becomes 255. A script that exits with 256 to signal an error reports success. Keep codes between 0 and 125, as the higher values have the special meanings shown above. The last.sh script returns 1, the status of its final grep, although it printed nothing alarming.

$ bash -c 'exit 3'; echo $?
3
$ bash -c 'exit 255'; echo $?
255
$ bash -c 'exit 256'; echo $?
0
$ bash -c 'exit 300'; echo $?
44
$ bash -c 'exit -1'; echo $?
255
$ cat last.sh
#!/bin/bash

echo "checking"
grep -q nosuchuser /etc/passwd
$ bash last.sh; echo $?
checking
1

Functions and return

Functions return a status like commands. The return builtin sets it explicitly; otherwise, a function returns the status of its last command.

cat func.sh
bash func.sh

is_number returns the status of the [[ ]] test, so it can be used directly in an if. check_port returns different codes for different problems, and writes its error messages to standard error with >&2. A function's output, not its return status, is the way to return data; the status is only for success or failure.

$ cat func.sh
#!/bin/bash

is_number() {
    [[ $1 =~ ^[0-9]+$ ]]
}

check_port() {
    if ! is_number "$1"; then
        echo "not a number: $1" >&2
        return 2
    fi
    if (( $1 < 1 || $1 > 65535 )); then
        echo "out of range: $1" >&2
        return 1
    fi
    echo "valid port: $1"
}

check_port 8080; echo "status $?"
check_port 70000; echo "status $?"
check_port http; echo "status $?"
$ bash func.sh
valid port: 8080
status 0
out of range: 70000
status 1
not a number: http
status 2

The && and || operators

cmd1 && cmd2 runs cmd2 only if cmd1 succeeds; cmd1 || cmd2 runs cmd2 only if cmd1 fails.

mkdir -p build && cd build && pwd
cd /nonexistent && echo "never printed"
cd /nonexistent 2> /dev/null || echo "cannot change directory"
true && false || echo "runs although the first command succeeded"

Chaining with && stops at the first failure. a && b || c is often used as a short if-then-else, but it is not one: c also runs when a succeeds and b fails, as the last line shows. Use a real if statement when b can fail.

$ mkdir -p build && cd build && pwd
/home/jano/work/build
$ cd /nonexistent && echo "never printed"
bash: cd: /nonexistent: No such file or directory
$ cd /nonexistent 2> /dev/null || echo "cannot change directory"
cannot change directory
$ true && false || echo "runs although the first command succeeded"
runs although the first command succeeded

Conditions are exit codes

The if statement runs a command and tests its exit code. ! inverts the status.

if grep -q jano /etc/passwd; then echo "jano exists"; fi
if ! id nosuchuser > /dev/null 2>&1; then echo "no such user"; fi
! true; echo $?

There is no need to write grep ...; if [ $? -eq 0 ]; any command can be the condition. [ and [[ are commands too, which return 0 or 1 depending on the test.

$ if grep -q jano /etc/passwd; then echo "jano exists"; fi
jano exists
$ if ! id nosuchuser > /dev/null 2>&1; then echo "no such user"; fi
no such user
$ ! true; echo $?
1

Exit codes of pipelines

The status of a pipeline is the status of its last command. Failures earlier in the pipeline are lost, unless we look at the PIPESTATUS array or enable the pipefail option.

false | true; echo $?
grep nosuch /nonexistent | sort; echo $?
grep nosuch /nonexistent | sort; echo "${PIPESTATUS[@]}"
set -o pipefail
false | true; echo $?
grep nosuch /nonexistent | sort; echo $?
set +o pipefail

The failing grep is hidden by the successful sort. PIPESTATUS holds the status of every command of the last pipeline. With pipefail, the pipeline returns the status of the last command that failed, or 0 if all succeeded.

$ false | true; echo $?
0
$ grep nosuch /nonexistent | sort; echo $?
grep: /nonexistent: No such file or directory
0
$ grep nosuch /nonexistent | sort; echo "${PIPESTATUS[@]}"
grep: /nonexistent: No such file or directory
2 0
$ set -o pipefail
$ false | true; echo $?
1
$ grep nosuch /nonexistent | sort; echo $?
grep: /nonexistent: No such file or directory
2
$ set +o pipefail

pipefail and SIGPIPE

pipefail has a side effect with commands such as head, which stop reading early.

set -o pipefail
yes | head -n 1; echo $?
seq 100000 | head -n 1; echo $?
set +o pipefail

After head exits, the writer gets the SIGPIPE signal when it writes again, and dies with status 141 (128 + 13). Without pipefail, this is invisible; with it, the pipeline fails although we got exactly what we wanted. Whether it happens depends on how much the writer produces before head exits. Where this matters, add || true or avoid early exit, for example with sed -n 1p, which reads all input.

$ set -o pipefail
$ yes | head -n 1; echo $?
y
141
$ seq 100000 | head -n 1; echo $?
1
141
$ set +o pipefail

Stopping on errors with set -e

By default, a script continues after a failed command. The set -e option (errexit) makes it exit when a command fails.

cat backup.sh
bash backup.sh; echo "exit: $?"
cat backup-e.sh
bash backup-e.sh; echo "exit: $?"

The first script cannot create the archive, yet it continues, reports backup done, and exits with 0; a cron job running it would never notice the problem. With set -e, the script stops at the failing tar and passes on its exit code, 2.

$ cat backup.sh
#!/bin/bash

echo "creating archive"
tar -czf /nonexistent/backup.tar.gz /etc/hostname 2> /dev/null
echo "removing old backups"
echo "backup done"
$ bash backup.sh; echo "exit: $?"
creating archive
removing old backups
backup done
exit: 0
$ cat backup-e.sh
#!/bin/bash

set -e

echo "creating archive"
tar -czf /nonexistent/backup.tar.gz /etc/hostname 2> /dev/null
echo "removing old backups"
echo "backup done"
$ bash backup-e.sh; echo "exit: $?"
creating archive
exit: 2

Where set -e does not apply

set -e is ignored in several contexts, which surprises many users.

cat pitfalls.sh
bash pitfalls.sh; echo "exit: $?"

Failures are not fatal in the condition of if, while, and until, in any command of a && or || list except the last, and in a command negated with !. The surprising part is that this extends to everything called from there: because check runs as an if condition, the false inside it does not stop the function, which continues and returns success. Only the last call of check, outside any condition, stops the script. Do not rely on set -e inside functions that are used as conditions; return explicit codes instead.

$ cat pitfalls.sh
#!/bin/bash

set -e

check() {
    false
    echo "check: still running after false"
}

if check; then
    echo "check succeeded"
fi

false || echo "false || ... is not fatal"
false && echo "never printed"
echo "false && ... is not fatal either"

check
echo "never reached"
$ bash pitfalls.sh; echo "exit: $?"
check: still running after false
check succeeded
false || ... is not fatal
false && ... is not fatal either
exit: 1

Arithmetic and set -e

The (( )) command returns 1 when the expression evaluates to zero.

cat count.sh
bash count.sh; echo "exit: $?"

((count++)) increments the counter, but the value of the expression is the old value, 0, so the command fails and set -e ends the script after the first file. Use ((++count)), count=$((count + 1)), or ((count++)) || true.

$ cat count.sh
#!/bin/bash

set -e

count=0
for f in /etc/hostname /etc/hosts; do
    echo "processing $f"
    ((count++))
done
echo "processed $count files"
$ bash count.sh; echo "exit: $?"
processing /etc/hostname
exit: 1

local hides the exit code

A command substitution in an assignment sets the status of the assignment. With local, export, or declare, the status is that of the builtin instead.

cat local.sh
bash local.sh; echo "exit: $?"

local value=$(cat ...) succeeds, because local succeeds, so the failed cat goes unnoticed and the function continues with an empty value. The plain assignment at the end passes on the failure and stops the script. Declare and assign in two steps: local value, then value=$(cat ...).

$ cat local.sh
#!/bin/bash

set -e

get_config() {
    local value=$(cat /nonexistent/app.conf)
    echo "value: '$value'"
}

get_config
echo "the error was not caught"

value=$(cat /nonexistent/app.conf)
echo "never reached"
$ bash local.sh; echo "exit: $?"
cat: /nonexistent/app.conf: No such file or directory
value: ''
the error was not caught
cat: /nonexistent/app.conf: No such file or directory
exit: 1

Commands that are allowed to fail

In strict mode, a command that returns non-zero for a normal result, such as grep without a match, ends the script.

cat errors.sh
bash errors.sh; echo "exit: $?"

The log file has no errors or warnings. grep -c prints 0 and returns 1 because nothing matched. The first call is protected with || true, the second is not, and the script dies silently, without any message. Mark commands that may legitimately fail with || true, or capture their status: grep ... || rc=$?.

$ cat errors.sh
#!/bin/bash

set -euo pipefail

errors=$(grep -c ERROR app.log || true)
echo "errors: $errors"

warnings=$(grep -c WARNING app.log)
echo "warnings: $warnings"
$ bash errors.sh; echo "exit: $?"
errors: 0
exit: 1

Unset variables with set -u

By default, an unset variable expands to an empty string. The set -u option (nounset) turns this into an error, which catches typos in variable names.

cat cleanup.sh
bash cleanup.sh; echo "exit: $?"
cat cleanup-u.sh
bash cleanup-u.sh; echo "exit: $?"
bash cleanup-u.sh /tmp/demo; echo "exit: $?"

The variable is misspelled, $wrokdir, so the first script works with /tmp/demo/ instead of a subdirectory. Had the command been rm -rf, the whole directory would be gone. With set -u, the typo stops the script with unbound variable. Optional values, such as command line arguments, need a default: ${1:-} expands to an empty string without an error, so the script can print its usage message.

$ cat cleanup.sh
#!/bin/bash

workdir=$1
echo "deleting /tmp/demo/$wrokdir"
ls -d "/tmp/demo/$wrokdir"
$ bash cleanup.sh; echo "exit: $?"
deleting /tmp/demo/
/tmp/demo/
exit: 0
$ cat cleanup-u.sh
#!/bin/bash

set -u

workdir=${1:-}
if [[ -z $workdir ]]; then
    echo "usage: cleanup-u.sh dir" >&2
    exit 2
fi
echo "deleting /tmp/demo/$wrokdir"
$ bash cleanup-u.sh; echo "exit: $?"
usage: cleanup-u.sh dir
exit: 2
$ bash cleanup-u.sh /tmp/demo; echo "exit: $?"
cleanup-u.sh: line 10: wrokdir: unbound variable
exit: 1

Tracing with set -x

The -x option (xtrace) prints every command, after expansion, before it is run. It can be enabled for a whole run with bash -x, or for a part of a script with set -x and set +x.

cat greet.sh
bash -x greet.sh Jan

Trace lines start with +; the extra + marks the command substitution, a nested level. The trace shows the actual values, here the hour, 21, which explains why the script did not say good morning. The trace goes to standard error.

$ cat greet.sh
#!/bin/bash

name=${1:-world}
hour=$(date +%H)
if (( 10#$hour < 12 )); then
    greeting="Good morning"
else
    greeting="Hello"
fi
echo "$greeting, $name"
$ bash -x greet.sh Jan
+ name=Jan
++ date +%H
+ hour=21
+ ((  10#21 < 12  ))
+ greeting=Hello
+ echo 'Hello, Jan'
Hello, Jan

Cleaning up with trap

The trap builtin runs a command when the shell receives a signal or reaches a certain point. The EXIT trap runs when the script ends for any reason, and the ERR trap when a command fails.

cat report.sh
bash report.sh; echo "exit: $?"
ls /tmp/report.*

The script creates a temporary file and registers its removal right away. When cat fails, the ERR trap prints the line number and the failed command, set -e ends the script, and the EXIT trap removes the temporary file, so nothing is left behind. Note the single quotes: $tmp, $LINENO, and $BASH_COMMAND are expanded when the trap runs, not when it is set.

$ cat report.sh
#!/bin/bash

set -euo pipefail

tmp=$(mktemp /tmp/report.XXXXXX)
trap 'rm -f "$tmp"' EXIT
trap 'echo "error on line $LINENO: $BASH_COMMAND" >&2' ERR

echo "collecting data into $tmp"
date > "$tmp"
cat /nonexistent/data.csv >> "$tmp"
echo "report ready"
$ bash report.sh; echo "exit: $?"
collecting data into /tmp/report.PiqpZi
cat: /nonexistent/data.csv: No such file or directory
error on line 11: cat /nonexistent/data.csv >> "$tmp"
exit: 1
$ ls /tmp/report.*
ls: cannot access '/tmp/report.*': No such file or directory

A strict mode script

The following script combines the techniques: strict mode, argument checking with a usage message and exit code 2, a temporary file with cleanup, and a meaningful exit code.

cat count-lines.sh
cat files.txt
bash count-lines.sh files.txt; echo "exit: $?"
bash count-lines.sh; echo "exit: $?"
echo "missing.txt" >> files.txt
bash count-lines.sh files.txt; echo "exit: $?"
ls /tmp/count.*

The script sums the line counts of the files listed in its argument. With a missing argument, it prints the usage and exits with 2, a common convention for usage errors. When one of the listed files does not exist, the redirection fails, the script stops instead of printing a wrong total, and the trap removes the temporary file. ${0##*/} is the script name without the directory.

$ cat count-lines.sh
#!/bin/bash

set -euo pipefail

if (( $# != 1 )); then
    echo "usage: ${0##*/} list-file" >&2
    exit 2
fi

list=$1
tmp=$(mktemp /tmp/count.XXXXXX)
trap 'rm -f "$tmp"' EXIT

while read -r file; do
    wc -l < "$file" >> "$tmp"
done < "$list"

total=$(awk '{ sum += $1 } END { print sum }' "$tmp")
echo "total lines: $total"
$ cat files.txt
/etc/passwd
/etc/group
$ bash count-lines.sh files.txt; echo "exit: $?"
total lines: 64
exit: 0
$ bash count-lines.sh; echo "exit: $?"
usage: count-lines.sh list-file
exit: 2
$ echo "missing.txt" >> files.txt
$ bash count-lines.sh files.txt; echo "exit: $?"
count-lines.sh: line 15: missing.txt: No such file or directory
exit: 1
$ ls /tmp/count.*
ls: cannot access '/tmp/count.*': No such file or directory

Common exit codes

CodeMeaning
0Success
1General error; for grep and diff: no match, files differ
2Misuse: invalid options or arguments; serious error for grep and diff
124Command stopped by timeout
126Command found but not executable
127Command not found
128 + NKilled by signal N: 130 Ctrl+C, 137 SIGKILL, 141 SIGPIPE, 143 SIGTERM
255Exit code out of range; also the code of ssh for connection errors

Best practices

Source

Bash manual: Exit Status, Bash manual: The Set Builtin

In this article, we have read exit codes with $?, looked at the special values for missing commands and signals, used exit codes in conditions, lists, and pipelines, and written scripts that stop on errors with set -euo pipefail and clean up with trap. See also the kill, job control, and redirection articles.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Linux tutorials.