How to check if there are no parameters provided to a command?
To check if there were no arguments provided to the command, check value of $#
variable then,
if [ $# -eq 0 ]; then
echo "No arguments provided"
exit 1
fi
If you want to use $*
(not preferable) then,
if [ "$*" == "" ]; then
echo "No arguments provided"
exit 1
fi
Some explanation:
The second approach is not preferable because in positional parameter expansion *
expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That means a string is constructed. So there is extra overhead.
On the other hand #
expands to the number of positional parameters.
Example:
$ command param1 param2
Here,
Value of $#
is 2 and value of $*
is string "param1 param2" (without quotes), if IFS is unset. Because if IFS is unset, the parameters are separated by spaces
For more details man bash
and read topic named Special Parameters
If you're only interested in bailing if a particular argument is missing, Parameter Substitution is great:
#!/bin/bash
# usage-message.sh
: ${1?"Usage: $0 ARGUMENT"}
# Script exits here if command-line parameter absent,
#+ with following error message.
# usage-message.sh: 1: Usage: usage-message.sh ARGUMENT