Check existence of input argument in a Bash shell script
In some cases you need to check whether the user passed an argument to the script and if not, fall back to a default value. Like in the script below:
scale=${2:-1}
emulator @$1 -scale $scale
Here if the user hasn't passed scale
as a 2nd parameter, I launch Android emulator with -scale 1
by default. ${varname:-word}
is an expansion operator. There are other expansion operators as well:
${varname:=word}
which sets the undefinedvarname
instead of returning theword
value;${varname:?message}
which either returnsvarname
if it's defined and is not null or prints themessage
and aborts the script (like the first example);${varname:+word}
which returnsword
only ifvarname
is defined and is not null; returns null otherwise.
It is:
if [ $# -eq 0 ]
then
echo "No arguments supplied"
fi
The $#
variable will tell you the number of input arguments the script was passed.
Or you can check if an argument is an empty string or not like:
if [ -z "$1" ]
then
echo "No argument supplied"
fi
The -z
switch will test if the expansion of "$1"
is a null string or not. If it is a null string then the body is executed.
Try:
#!/bin/bash
if [ "$#" -eq "0" ]
then
echo "No arguments supplied"
else
echo "Hello world"
fi
It is better to demonstrate this way
if [[ $# -eq 0 ]] ; then
echo 'some message'
exit 1
fi
You normally need to exit if you have too few arguments.