Controlling when to exit a shell script

The exit statement will exit the current shell script. It can be given a numeric argument which is the script's exit status. If omitted the exit status of the last run command is used. 0 (zero) signifies success, non-zero signifies failure. For example:

   #!/bin/sh
   if [ $# -ne 2 ]
   # "$#" is number of parameters- here we test
   # whether it is not equal to two
   then
   echo "Usage $0 \<file1\> \<file2\>"	# not two parameters
   # so print message
   exit 2             		# and fail ($0 is
   # name of command).
   fi
   ...<rest of script>

This script is supposed to take two positional arguments. It will exit with status 2 (error) rather than 0 (success) if it is not called with two parameters.


[Home] [Search] [Index] This site maintained by unixhelp@mathcs.duq.edu