Exit command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Revision as of 05:33, 10 June 2020 by Admin (talk | contribs)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

← Create usage messagesHomeThe case statement →

Sometimes we need to stop the execution of our script when a condition is satisfied. For example, if tar command not installed, stop the execution of our shell script. We can also take action based on the exit code of the command. Say if ping command is successful, continue with script or exit with an error. Let us see how to use the exit command and the exit statuses in our scripts.

Purpose

Exit the bash shell.

Syntax

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:

Examples

#!/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 →