Find exit status code of last executed command on Linux and Unix

When we execute any command or script,it returns an exit status. The exit status is also called as return code or exit code. It is important to know the exit status of command which we execute.
The method which we are going to describe become more helpful with script also.

Exit status must be an integer in the 0 – 255 range.

The exit status with zero value considered as command or script has run execution.Whereas, the exit status with non-zero value meaning is the command or script is not run successfully.

Exit status code of last executed command

To get the exit status code,run the below given command after running the script/command.

echo $?

See below given Screenshot
In this example I tried to show, how we can use echo $? to check the exit code.

When I used the command ls -lhrt and after this I use echo $? which show the output as 0 (i.e Zero). It means the last command (ls -lhrt) was executed successfully.
Whereas on using wrong command,exit code is non-zero (i.e 127 as shown on terminal)

exit code status

Bash script example with exit code

The below given bash script is created, to check the exit status of command.The script is a reference and can be used in other bash script as per the requirement.

## This script is a sample for using "exit $?" command within script
echo "Type any command and hit ENTER"
read val
$val > /dev/null 2>&1
### putting 4 seconds delay by using sleep command
if [ $? != 0 ]
echo "**************************************************************"
echo "*************************************************************"
echo 'The command is SUCCESSFULLY executed'

See below given animated example

exit code linux unix

2 thoughts on “Find exit status code of last executed command on Linux and Unix”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.