What is exit status in the linux?
Whenever you fire a shell command it returns a status to check if that command was successful or not – exit status can be very useful in scripts to make you scripts stable.
Example:-
In the example below, I ran uptime command and it was successful – so when I checked the exit status using echo $? it showed 0.
[root@server ~]# uptime
05:15:27 up 50 days, 16:53, 1 user, load average: 0.08, 0.03, 0.08
[root@server ~]# echo $?
0
[root@server ~]#
Now let’s see what happens when command is not successful.
So in the example below, I typed incorrect command and exit status was other than 0 – which indicates error.
[root@server ~]# uptimee
-bash: uptimee: command not found
[root@server ~]# echo $?
127
[root@server ~]#
Practical usage in shell scripting.
#!/bin/bash
cd $1 > /dev/null 2>&1
if [ $? != 0 ]
then
echo "Directory Not Found" ; exit
fi
echo "Great!"
So, above script terminates if cd command is not successful.
If it’s successful it will execute further code.
[root@server ~]# ./exitstatus.sh /tmp
Great!
[root@server ~]# ./exitstatus.sh /tmpp
Directory Not Found
[root@server ~]#