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.

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

Sample output if no arguments are specified :

$ ./find_ns.sh
Usage: ./find_ns.sh domain_name

Sample output if an argument is passed:

$ ./find_ns.sh shellhacks.com
ns2.ukraine.com.ua.
ns3.ukraine.com.ua.
ns1.ukraine.com.ua.