Difference between revisions of "Exit command"

From Linux Shell Scripting Tutorial - A Beginner's handbook
Jump to navigation Jump to search
 
(7 intermediate revisions by the same user not shown)
Line 5: Line 5:
 
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.
 
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==
 
==Purpose==
Exit the [[bash]] shell.  
+
Exit the [[bash]] shell or shell script with a status of N.
 +
 
 
==Syntax==
 
==Syntax==
 
The syntax is as follows:
 
The syntax is as follows:
Line 14: Line 15:
 
* If N is omitted, the exit status is that of the last command executed.  
 
* 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.
 
* 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:
+
* If N is set to 0  means normal shell exit.  
 
==Examples==
 
==Examples==
 +
Create a shell script called exitcmd.sh:
 
<syntaxhighlight lang="bash" >#!/bin/bash
 
<syntaxhighlight lang="bash" >#!/bin/bash
 
echo "This is a test."
 
echo "This is a test."
Line 27: Line 29:
 
To see exit status of the script, enter (see [[the exit status of a command]] for more information about special  shell variable $?) :
 
To see exit status of the script, enter (see [[the exit status of a command]] for more information about special  shell variable $?) :
 
<syntaxhighlight lang="bash" >echo $?</syntaxhighlight>
 
<syntaxhighlight lang="bash" >echo $?</syntaxhighlight>
 +
<p>[[File:Linux bash exit command and exit codes demo.png|thumb|frame|center|Linux bash exit command and exit codes demo]]</p>
 
===Exit status at the CLI===
 
===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:
 
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:
<syntaxhighlight lang="bash" >ping -q -c 4 www.cyberciti.biz >/dev/null
+
<syntaxhighlight lang="bash" >$ ping -q -c 4 www.cyberciti.biz >/dev/null
echo $?</syntaxhighlight>
+
$ echo $?</syntaxhighlight>
 
Output:
 
Output:
 
<pre>0</pre>
 
<pre>0</pre>
Line 37: Line 40:
 
## will get the exit status of the last command in the pipeline ##
 
## will get the exit status of the last command in the pipeline ##
 
echo $?</syntaxhighlight>
 
echo $?</syntaxhighlight>
 +
===Execute commands based upon  the exit status===
 +
Run command2 if command1 is successful using [[Logical AND]] (<kbd>&&</kbd>) operator:
 +
<syntaxhighlight lang="bash" >command1 && command2</syntaxhighlight>
 +
For example, if wget command found in execute the [[echo command]]
 +
<syntaxhighlight lang="bash" >$ type -a wget >/dev/null && echo "wget command found. Download the Linux kernel ..."</syntaxhighlight>
 +
Similarly, bar command is executed if, and only if, foo command returns a non-zero exit status using [[Logical OR]] operator:
 +
<syntaxhighlight lang="bash" >$ foo || bar</syntaxhighlight>
 +
Therefore we can combine bash Exit command and exit codes to build quick logic as follows:
 +
<syntaxhighlight lang="bash" >$ 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"</syntaxhighlight>
 +
We can group commands as a unit as follows:
 +
<syntaxhighlight lang="bash" >##  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";
 +
                            }</syntaxhighlight>
  
 
==Shell script example==
 
==Shell script example==
Line 46: Line 71:
 
echo "Trying to backup ${BAK} directory to tape device ${TAPE} .."
 
echo "Trying to backup ${BAK} directory to tape device ${TAPE} .."
  
# See if $BAK exits or not else die
+
# See if $BAK directory exists or not, else die
 
# Set unsuccessful shell script termination with exit status # 1
 
# Set unsuccessful shell script termination with exit status # 1
 
[ ! -d $BAK ] && { echo "Source backup directory $BAK not found."; exit 1; }
 
[ ! -d $BAK ] && { echo "Source backup directory $BAK not found."; exit 1; }
  
# See if $TAPE device exits or not else die
+
# See if $TAPE device exists or not, else die
 
# Set unsuccessful shell script termination with exit status # 2
 
# Set unsuccessful shell script termination with exit status # 2
 
[ ! -b $TAPE ] && { echo "Backup tape drive $TAPE not found or configured."; exit 2; }
 
[ ! -b $TAPE ] && { echo "Backup tape drive $TAPE not found or configured."; exit 2; }
Line 70: Line 95:
 
./datatapebackup.sh
 
./datatapebackup.sh
 
echo $?</syntaxhighlight>
 
echo $?</syntaxhighlight>
 +
All of our shell commands return an exit code when terminated successfully or abnormally. We can use the exit command in our shell script to provide the exit code. We also learned how to harness the exit status's power to build logic in a shell script or at the command line.
 +
 
[[Category:Conditional Execution]][[Category:Commands]][[Category:Built in Bash commands‏‎]]
 
[[Category:Conditional Execution]][[Category:Commands]][[Category:Built in Bash commands‏‎]]
  

Latest revision as of 11:03, 11 June 2020

← 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 or shell script with a status of N.

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.

Examples

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

Linux bash exit command and exit codes demo

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 directory exists 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 exists 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 $?

All of our shell commands return an exit code when terminated successfully or abnormally. We can use the exit command in our shell script to provide the exit code. We also learned how to harness the exit status's power to build logic in a shell script or at the command line.

← Create usage messagesHomeThe case statement →