Print Usage and Exit if Arguments are Not Provided

Use the following test in your shell scripts to:

1. verify the number of input values

2. display an error message if the number of input argument is not correct

3. exit a shell script with the error status

[ $# -eq 0 ] && { echo "Usage: $0 argument"; exit 1; }
Parameter Description
$# variable tells the number of input arguments the script was passed
-eq 0 check if the number of input arguments is equal zero
$0 returns the path to your shell script

Bash Script Example

The following script is using dig command to find the name server of a domain name. The domain name should be provided as an argument.

[ $# -eq 0 ] && { echo "Usage: $0 domain_name"; exit 1; }
dig NS $domain @ +short

Sample output if no arguments are specified :

$ ./
Usage: ./ domain_name

Sample output if an argument is passed:

$ ./

2 Replies to “Print Usage and Exit if Arguments are Not Provided”

  1. Always write error message to stderr:

    { echo “Usage: $0 domain_name” >&2; exit 1; }

  2. You should write usage to stderr only when user tried invalid options and args. If they specify a “-h” option should write to stdout. Replying to previous post since you shouldn’t ALWAYS write to stderr, there are some exceptions.

Leave a Reply