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.
Always write error message to stderr:
{ echo “Usage: $0 domain_name” >&2; exit 1; }
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.
Martin specified “error message”. When you use “-h”, that is not an error message. The return status for such a call is generally “0”. So his comment is correct. Nevertheless, it was worth mentioning that usage messages don’t always go on stderr.