Bash Exit Codes
What is an Exit Code?
Every command returns a number when it finishes, called the exit code (or exit status).
0means the command succeeded- Any other number (1-255) means something went wrong
Read the Exit Code ($?)
The special variable $? holds the exit code of the last command:
Example: A Failing Command
ls missing.txt
ls: cannot access 'missing.txt': No such file or directory
echo $?
2
$? changes after every command, so read it right away, or save it in a variable: status=$?.
Set the Exit Code (exit)
Use exit with a number to end a script and return that exit code:
Example: Exit with an Error
Save this as check.sh:
#!/bin/bash
if [ ! -f config.txt ]; then
echo "config.txt not found"
exit 1
fi
echo "Config found"
Run it:
./check.sh
config.txt not found
Run Only on Success (&&)
&& runs the next command only if the first one succeeded (exit code 0):
Example: Create a Folder, Then Enter It
mkdir backup && cd backup && pwd
/home/user/backup
Run Only on Failure (||)
|| runs the next command only if the first one failed:
Example: Show a Message on Failure
cat missing.txt 2> /dev/null || echo "File not found"
File not found
Use Exit Codes in if
An if statement can test a command directly. The if block runs when the command's exit code is 0:
Example: Test a Command
Save this as search.sh:
#!/bin/bash
if grep -q "Emma" names.txt; then
echo "Emma is on the list"
else
echo "Emma is not on the list"
fi
Run it:
./search.sh
Emma is on the list
The -q option makes grep quiet: it prints nothing and only sets the exit code.
Stop on the First Error (set -e)
By default, a script keeps running after a command fails. Add set -e at the top to stop the script as soon as a command fails:
Example: Stop on Error
Save this as strict.sh:
#!/bin/bash
set -e
echo "Step 1"
ls missing.txt
echo "Step 2"
Run it:
./strict.sh
Step 1
ls: cannot access 'missing.txt': No such file or directory
"Step 2" is never printed, because the script stopped when ls failed.
Common Exit Codes
0: Success1: General error2: Wrong use of a command (for example a bad option)126: The command exists but cannot be run (no permission)127: Command not found130: The script was stopped with Ctrl+C