Exit codes make it easier to diagnose issues when a script fails.
sysexits.h
helps align your scripts with broader industry practices.After running a command, check its exit stautus code with:
echo $?
Use case statements to act on specific, custom exit codes:
my_command
case $? in
0) echo "Success!";;
1) echo "General error occurred.";;
127) echo "Command not found.";;
*) echo "Unhandled exit code.";;
esac
In custom scripts, define meaningful exit codes to signal specific issues:
EX_USAGE=64
EX_FILE_NOT_FOUND=66
EX_SUCCESS=0
if [ ! -f "$1" ]; then
echo "File not found!"
exit $EX_FILE_NOT_FOUND
fi
&&
and ||
#Use &&
to run a command only if the previous command succeeds and ||
to handle failures:
command && echo "Success" || echo "Failure"
Exit immediately with a meaningful status if an error is detected:
if [ -z "$variable" ]; then
echo "Error: Variable is unset!"
exit 1
fi
Ensure resources (e.g., temp files) are cleaned up, even if a script exits prematurely:
trap 'rm -f /tmp/myfile; exit' INT TERM EXIT
command || exit 1
Handle failures within loops:
for file in *.txt; do
process "$file"
if [ $? -ne 0 ]; then
echo "Error processing $file"
exit 1
fi
done
Exit codes >128
usually represent signals (128 + signal number
), e.g., 130
means the script was terminated by SIGINT.
Enable stricter error handling with set options:
set -e
: Exit on any error.set -u
: Treat undefined variables as errors.set -o pipefail
: Detect errors in pipelines.Sources and recommended, further resources on the topic:
License: List of Linux exit status codes by Jonas Jared Jacek is licensed under CC BY-SA 4.0.
This license requires that reusers give credit to the creator. It allows reusers to distribute, remix, adapt, and build upon the material in any medium or format, for noncommercial purposes only. To give credit, provide a link back to the original source, the author, and the license e.g. like this:
<p xmlns:cc="http://creativecommons.org/ns#" xmlns:dct="http://purl.org/dc/terms/"><a property="dct:title" rel="cc:attributionURL" href="https://www.ditig.com/publications/linux-exit-status-codes">List of Linux exit status codes</a> by <a rel="cc:attributionURL dct:creator" property="cc:attributionName" href="https://www.j15k.com/">Jonas Jared Jacek</a> is licensed under <a href="https://creativecommons.org/licenses/by-sa/4.0/" target="_blank" rel="license noopener noreferrer">CC BY-SA 4.0</a>.</p>
For more information see the DITig legal page.