When writing Bash scripts, you will frequently need to stop the execution of a script when a certain condition is met or perform some actions based on a command's exit code.
In this article we will go over the built-in bash exit command as well as the exit status codes of the commands that have been executed.
BONUS
Stay tuned until the end of this guide for something special: a free copy of my Bash Scripting Handbook.
Exit Status Code
When a shell command exits, whether successfully without any errors or unsuccessfully with errors, it returns an exit code.
An exit code of zero indicates that the command was completed properly without any errors, while a non-zero indicates that an error occurred.
The $? is a special shell variable that stores the exit status of the most recently run command:
cat manifesto.txt
echo $?
# output
A Gentle reminder, I use Arch BTW!
0
Because the cat command was completed successfully and without error, the exit code is zero, as expected.
If you attempt to run cat command on a not-existing file, the exit code will be non-zero as shown below:
cat no-file
echo $?
# output
cat: no-file: No such file or directory
1
As expected, the exist status code is non-zero.
The exit status code of a command can be used for debugging and determining the reason for its failure. The man pages for each command provide information about the exit codes. When chaining commands using pipes, the exit status code is that of the last command in the chain.
Keep reading with a 7-day free trial
Subscribe to sysxplore to keep reading this post and get 7 days of free access to the full post archives.