How To Set And Check Exit Status of Command in Linux

This post will guide you how to set exit status in bash shell script. How do I check exit status of a command from the command line in your Linux operating system.

Set And Check Exit Status of Command in Linux 1

What is Exit Status?


Each Linux or Unix command will return a exit code while terminating. and this exit code is a numeric value varies from 0 to 255. And it also be called an exit code or exit status. So Any Linux command or shell script will have an exit status or exit code. If a Linux command or bash shell script terminates normally, and it will return a exit code as number 0. otherwise, it will return an non-zero value.

Exit Code:

Code        Description
0           success
1-255       failure (in general)
126         the requested command (file) can't be executed (but was found)
127         command (file) not found
128         according to ABS it's used to report an invalid argument to the exit uiltin, but I wasn't able to verify that in the source code of Bash (see code 255)
128 +        N the shell was terminated by the signal N (also used like this by various other programs)
255          wrong argument to the exit builtin (see code 128)

Checking Exit Status of Command


If you want to get exit code or exit status of a linux command, and you can run echo $? command to get the status of executed command. for exmaple, if you have executed one command called “df -h“, then you want to get the exit status of this command, just type the following command:

$ echo $?

Outputs:

[devops@mydevops ~]$ df -h
Filesystem Size Used Avail Use% Mounted on
devtmpfs 648M 0 648M 0% /dev
tmpfs 663M 0 663M 0% /dev/shm
tmpfs 663M 9.5M 654M 2% /run
tmpfs 663M 0 663M 0% /sys/fs/cgroup
/dev/mapper/cl_mydevops-root 41G 4.6G 36G 12% /
/dev/mapper/cl_mydevops-home 20G 299M 20G 2% /home
/dev/sda1 976M 133M 777M 15% /boot
tmpfs 133M 28K 133M 1% /run/user/42
tmpfs 133M 2.3M 131M 2% /run/user/1000

[devops@mydevops ~]$ echo $?
0

From the above outputs, you can see that a number 0 is returned. it indicated that the above command df -h is exectued successfully.

You can also use the exit status in the conditional IF statement in shell script. For example, you created a file using touch command, and then you want to check if this file is created successfully. how to check it. You can use the exit status of the above touch command, if the exit code is 0, it indicates that that file is created. see below shell script:

#! /bin/bash

touch /tmp/mytext.txt
ecode=$?
if [ $ecode -eq 0 ]
then 
echo "file created!"
else
echo "failed to create file!"
fi

then you can execute this script, see the below outputs:

[devops@mydevops ~]$ ./mytest.sh
file created!
[devops@mydevops ~]$

Conclusion


You should know that how to check exit status or exit code of a linux command or shell script in your CentOS or RHEL Linux system.

 

You might also like:

Sidebar



back to top