Shell Exit Codes
An exit code is the number a command hands back when it finishes. 0 means success, and any other number means something went wrong.
A command that succeeds
A good ls leaves the code 0.
ls notes.txt
echo $?A command that fails
A missing file leaves a code other than 0.
ls missing.txt 2>/dev/null
echo $?Codes from grep
Grep leaves 0 for a match and 1 for no match.
grep -q "milk" shopping.txt
echo $?
grep -q "butter" shopping.txt
echo $?Exit a script with a code
Exit 3 ends the script, and the line after it never runs.
cat > fail.sh <<'EOF'
#!/bin/bash
echo "Before exit"
exit 3
echo "After exit"
EOF
chmod +x fail.sh
./fail.sh; echo $?Stop at the first failure
With set -e, the failed ls ends the script.
cat > safe.sh <<'EOF'
#!/bin/bash
set -e
echo "First line"
ls missing.txt 2>/dev/null
echo "This never prints"
EOF
chmod +x safe.sh
./safe.sh; echo $?Example
cat > check.sh <<'EOF'
#!/bin/bash
if [ -f notes.txt ]; then
echo "notes.txt found"
exit 0
else
echo "notes.txt missing"
exit 1
fi
EOF
chmod +x check.sh
./check.sh
echo $?Key points
- Exit code: every command ends with a number, and 0 means success.
- Last code: $? holds the exit code of the last command.
- Use exit N to end a script with the code N.
- Set -e: set -e stops a script at the first command that fails.
In this example, the script tests notes.txt. The file exists, so it prints notes.txt found and exits with 0. Then echo $? shows that code.
Note
Check $? at once, because the next command replaces it.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
A command ends with exit code 0. What does that mean?