Each command in Linux returns a status when it terminates normally or the other way. You can use these exit statuses mostly in shell scripts to further determine the course of your shell script. We will see a detailed explanation of the exit status further but here is a short example:-
You write a shell script, which changes the directory and runs some commands, however, what if the change directory fails? the shell script will still run the further commands, which can create a mess. However, you can put an if statement using the exit status, and make sure to break the script if the change directory fails.
So as we learned a shell command returns a status, you can use that status to check if the command was successful. It can be very useful to make your scripts stable.
How to see the status of the command?
So on the command line, you can use the command below to check the status of the previous commands.
If the command above returns the value 0 then the previous command was successful, if it returns any other number that means it wasn’t successful.
Let’s see this with a practical example.
In the example below, I ran the uptime command and it was successful – so when I checked the exit status using echo $? it showed 0.
[[email protected] ~]# uptime 05:15:27 up 50 days, 16:53, 1 user, load average: 0.08, 0.03, 0.08 [[email protected] ~]# echo $? 0 [[email protected] ~]#
Now let’s see what happens when the command is not successful.
So in the example below, I typed incorrect command and the exit status was other than 0 – which indicates an error.
[[email protected] ~]# uptimee -bash: uptimee: command not found [[email protected] ~]# echo $? 127 [[email protected] ~]#
How do I use exit status in shell scripts?
Let’s see the practical usage in shell scripting of Exit Status in Linux with an example. I am writing a script that requires changing the directory and then performing some actions. I want the script to exit if the change directory is failed.
So what I have done is first fired the cd command and then I checked the exit status of the command.
#!/bin/bash cd $1 > /dev/null 2>&1 if [ $? != 0 ] then echo "Directory Not Found" ; exit fi echo "Great!"
So, the above script terminates if the cd command is not successful. If it’s successful it will execute further code.
[[email protected] ~]# ./exitstatus.sh /tmp Great! [[email protected] ~]# ./exitstatus.sh /tmpp Directory Not Found [[email protected] ~]#