I am a new Linux system user. How do I get the exit code of a command? How do I get the exit code or status of Linux or Unix shell command and store it into a shell variable?
Introduction – Each Linux or Unix shell command returns a status when it terminates normally or abnormally. For example, if backup.sh script is unsuccessful, and it returns a code which tells the shell script to send an e-mail to sysadmin.
What is an exit code in bash shell?
Every Linux or Unix command executed by the shell script or user has an exit status. Exit status is an integer number. 0 exit status means the command was successful without any errors. A non-zero (1-255 values) exit status means command was a failure.
How to find out the exit code of a command
You need to use a particular shell variable called $? to get the exit status of the previously executed command. To print $? variable use the echo command or printf command: date echo $? date-foo-bar printf '%dn' $?
From the above outputs, it is clear that the exit code is 0 indicates that date command was successful. Further, the exit code is 127 (non-zero) as the nonexistant-command was not successful.
Bash get exit code of command – How to use exit codes in shell scripts
So how do you store exit status of the command in a shell variable? Simply assign $? to a shell variable. The syntax is:
commandstatus=$?## run date command ##cmd="date"$cmd## get status ##status=$?## take some decision ## [$status-eq0]&&echo"$cmd command was successful"||echo"$cmd failed"
## run date command ##
## get status ##
## take some decision ##
[ $status -eq 0 ] && echo "$cmd command was successful" || echo "$cmd failed"
How do I set an exit code for my own shell scripts?
The exit command cause normal shell script termination. It exits the shell with a status of N. The syntax is:
A sample shell script to get the exit code of a command
#!/bin/bash## Sample shell script to demo exit code usage ##set-e## find ip in the file ##grep-q 192.168.2.254 /etc/resolv.conf
## Did we found IP address? Use exit status of the grep command ##if[$?-eq0]thenecho"Success: I found IP address in file."exit0elseecho"Failure: I did not found IP address in file. Script failed">&2exit1fi
# Sample shell script to demo exit code usage #
set -e ## find ip in the file ##
grep -q 192.168.2.254 /etc/resolv.conf ## Did we found IP address? Use exit status of the grep command ##
if [ $? -eq 0 ]
echo "Success: I found IP address in file."
echo "Failure: I did not found IP address in file. Script failed" >&2
How to deal with the exit codes of all piped commands
The author is the creator of nixCraft and a seasoned sysadmin, DevOps engineer, and a trainer for the Linux operating system/Unix shell scripting. Get the latest tutorials on SysAdmin, Linux/Unix and open source topics via RSS/XML feed or weekly email newsletter.