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 :
$ ./