Bash get exit code of command on a Linux / Unix
I am a brand new Linux system person. How do I get the exit code of a command? How do I get the exit code or standing of Linux or Unix shell command and retailer it right into a shell variable?
Introduction – Every Linux or Unix shell command returns a standing when it terminates usually or abnormally. For instance, if backup.sh script is unsuccessful, and it returns a code which tells the shell script to ship an e-mail to sysadmin.
What’s an exit code in bash shell?
Each Linux or Unix command executed by the shell script or person has an exit standing. Exit standing is an integer quantity. zero exit standing means the command was profitable with none errors. A non-zero (1-255 values) exit standing means command was a failure.
The best way to discover out the exit code of a command
You want to use a selected shell variable known as $? to get the exit standing of the beforehand executed command. To print $? variable use the echo command or printf command:
printf ‘%dn’ $?
The best way to get the exit code of a command similar to date and date-foo-bar
From the above outputs, it’s clear that the exit code is zero signifies that date command was profitable. Additional, the exit code is 127 (non-zero) because the nonexistant-command was not profitable.
Bash get exit code of command – The best way to use exit codes in shell scripts
So how do you retailer exit standing of the command in a shell variable? Merely assign $? to a shell variable. The syntax is:
## run date command ##
## get standing ##
## take some choice ##
[ $standing -eq zero ] && echo “$cmd command was profitable” || echo “$cmd failed”
How do I set an exit code for my very own shell scripts?
The exit command trigger regular shell script termination. It exits the shell with a standing of N. The syntax is:
[ $? -eq zero ] || exit 1
A pattern shell script to get the exit code of a command
# Pattern shell script to demo exit code utilization #
## discover ip within the file ##
grep -q 192.168.2.254 /and many others/resolv.conf
## Did we discovered IP deal with? Use exit standing of the grep command ##
if [ $? -eq zero ]
echo “Success: I discovered IP deal with in file.”
echo “Failure: I didn’t discovered IP deal with in file. Script failed” >&2
The best way to cope with the exit codes of all piped instructions
See “Bash Discover out the exit codes of all piped instructions” for more information.
This web page confirmed the best way to use exit codes on Linux or Unix primarily based system and the best way to get the exit standing/code of command. For more information see: