Exit command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to: navigation, search
← Create usage messagesHomeThe case statement →

The syntax is as follows:

 exit N
  • The exit statement is used to exit from the shell script with a status of N.
  • Use the exit statement to indicate successful or unsuccessful shell script termination.
  • The value of N can be used by other commands or shell scripts to take their own action.
  • If N is omitted, the exit status is that of the last command executed.
  • Use the exit statement to terminate shell script upon an error.
  • If N is set to 0 means normal shell exit. Create a shell script called exitcmd.sh:
#!/bin/bash
echo "This is a test."
# Terminate our shell script with success message
exit 0

Save and close the file. Run it as follows:

chmod +x exitcmd.sh
./exitcmd.sh

Sample outputs:

This is a test.

To see exit status of the script, enter (see the exit status of a command for more information about special shell variable $?) :

echo $?

Shell script example

  • Any non zero value indicates unsuccessful shell script termination.
  • Create a shell script called datatapebackup.sh:
#!/bin/bash
BAK=/data2
TAPE=/dev/st0
echo "Trying to backup ${BAK} directory to tape device ${TAPE} .."
 
# See if $BAK exits or not else die
# Set unsuccessful shell script termination with exit status # 1
[ ! -d $BAK ] && { echo "Source backup directory $BAK not found."; exit 1; }
 
# See if $TAPE device exits or not else die
# Set unsuccessful shell script termination with exit status # 2
[ ! -b $TAPE ] && { echo "Backup tape drive $TAPE not found or configured."; exit 2; }
 
# Okay back it up
tar cvf $TAPE $BAK 2> /tmp/error.log
 
if [ $? -ne 0 ]
then
   # die with unsuccessful shell script termination exit status # 3
   echo "An error occurred while making a tape backup, see /tmp/error.log file".
   exit 3 
fi
 
# Terminate our shell script with success message i.e. backup done!
exit 0

Save and close the file. Run it as follows:

chmod +x datatapebackup.sh
./datatapebackup.sh
echo $?
← Create usage messagesHomeThe case statement →