The exit status in shell scripting

The exit status in shell scripting

In this tutorial we will discuss about the exit status in shell scripting.

Like in the C programs, the exit command terminates a script. It can also return a value which is read by the script’s parent process.

The exit status is also known as return status or exit code. By convention, a succesfull command returns 0, while an unsuccesfull command returns an integer between 1 and 255.

When a script ends with exit without any parameter, or exit $? or no exit at all, the script’s exit status is the same as the last command’s (in the script)  exit code:

The following script does not end with exit (notice that the exit lines are commented):

#!/bin/bash
FIRST_COMMAND
...
LAST_COMMAND
#exit
#exit $?
#This script will exit with the status of the last command!

The $? parameter gives the script the exit status of the last command executed in the function.

We have this script:

#!/bin/bash
echo "Hello world"
exit $? # This will return 0 because the command is valid.
gcc # Wrong command
echo $? # This will return a non-zero value because the command is not used propperly
useradd
exit 12 # This will return 12 to the shell
# to check this, type "echo $?" after the script shell terminates execution

In the next script, I will use ! to negate commands and show you what happens when we use commands combined with pipes:

#!/bin/bash
true #builtin true command
echo "the exit status of true is $?" # 0 : success
!true ## the ! negates the true command and the exit code
echo "the exit status of !true is $?' # 1 : error
### Using pipes: ! combined with pipe inverts the exit status returned
ls | X #invalid command
echo $? # 1 : error
!ls | X # NOT invalid command
echo $? # 0
# the exit code of this script is 0 ;
#type "echo $?" after the script finishes execution to check it

We have even more interesting shell scripting articles!

Was this Tutorial helpful? Help others share on Facebook, Twitter, and Google Plus!

 
Enjoyed this video?
The exit status in shell scripting
"No Thanks. Please Close This Box!"