I need to check the existence of an input argument. I have the following script
if [ "$1" -gt "-1" ]
then echo hi
fi
I get
[: : integer expression expected
How do I check the input argument1 first to see if it exists?
I need to check the existence of an input argument. I have the following script
if [ "$1" -gt "-1" ]
then echo hi
fi
I get
[: : integer expression expected
How do I check the input argument1 first to see if it exists?
I often use this snippet for simple scripts:
Another way to detect if arguments were passed to the script:
Note that
(( expr ))
causes the expression to be evaluated as per rules of Shell Arithmetic.In order to exit in the absence of any arguments, one can say:
Another (analogous) way to say the above would be:
help let
says:Try:
If you're only interested in detecting if a particular argument is missing, parameter substitution is great:
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:
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.Only because there's a more base point to point out I'll add that you can simply test your string is null:
Likewise if you're expecting arg count just test your last:
and so on with any arg or var
If you'd like to check if the argument exists, you can check if the # of arguments is greater than or equal to your target argument number.
The following script demonstrates how this works
test.sh
produces the following output