In this article, we cover exit status of a command in Bash. When we execute a command, it returns an exit status to the system. Through a commands’ exit status, we can deduce whether it was successfully executed or not. So, when the exit status is returned as zero that means the command was executed successfully. Non-zero exit status would convey otherwise.
There could be numerous reasons why a command won’t successfully be executed. It could be a typographical error, non-existent arguments, options etc.
Furthermore, a command can have more than one non-zero exit status codes. While it will always be a zero (0), if a command gets executed.
Check for exit status of a command in Bash
We can check for exit status code of a command through the following –
echo $?
Bash would automatically set the exit status code to $? variable for the last command to be executed. The output of the above code would either return a zero or non-zero value.
Let’s understand it with the help of an example. Copy a non-existent text file to the directory /dev/shm –
cp non-existent-file.txt /dev/shm
On the terminal, it would return with –
cp: cannot stat 'non-existent-file.txt': No such file or directory
Clearly, the file doesn’t exist. And, for the exit status –
echo $?
It may return with the exit status code –
1
Clearly, it was an unsuccessful execution. This time around, we check for the opposite. Create an empty text file through touch command in the directory /dev/shm –
touch /dev/shm/test-file.txt
Now, check for the exit status –
echo $?
It should return with –
0
Reason: When we tried to copy a non-existent file, the command could complete its operation. But, this time around we created an empty file which lead to successful execution of the command. Hence, the exit code status as zero (0).
In conclusion, we have covered here how to check exit status of a command in Bash.