Exit command

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search

← 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 $?

Exit status at the CLI

Exit status is not limited to shell script. Every time command terminated shell gets an exit code indicating success or failure of the command. Hence we can use the particular bash variable $? to get the exit status of the command. For instance:

$ ping -q -c 4 www.cyberciti.biz >/dev/null
$ echo $?

Output:

0

In this example, we will see the exit status of the last command (command3) only:

command1 | command2 | command3
## will get the exit status of the last command in the pipeline ##
echo $?

Execute commands based upon the exit status

Run command2 if command1 is successful using Logical AND (&&) operator:

command1 && command2

For example, if wget command found in execute the echo command

$ type -a wget >/dev/null && echo "wget command found. Download the Linux kernel ..."

Similarly, bar command is executed if, and only if, foo command returns a non-zero exit status using Logical OR operator:

$ foo || bar

Therefore we can combine bash Exit command and exit codes to build quick logic as follows:

$ my_command && echo "Done" || echo "Failed"
$ /usr/bin/rsnapshot daily && echo "Backup successful" || echo "Backup failed. Alerting OPS team..."
$ mkdir /opt/kernel && cd $_ && echo "Directory created and you are in $PWD"

We can group commands as a unit as follows:

##  Execute conditional command  using the [[ and Logical AND ##
[ -f /path/to/file ] && { echo "File found. Starting ...";
                          /path/to/command2;
                          /path/to/command3 arg1 arg2;
                        }
## another example 
 [[ "$value" != "Yes" ]] && { 
                              _errs=("${_errs[@]}" "<p>The I/O thread for reading the master's binary log not found ($v: $value)</p>");
                              _is_error_found="true"; 
                             }

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 →