Check existence of input argument in a Bash shell script
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?
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.
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.
If you're only interested in detecting 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
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 undefined varname
instead of returning the word
value; ${varname:?message}
which either returns varname
if it's defined and is not null or prints the message
and aborts the script (like the first example); ${varname:+word}
which returns word
only if varname
is defined and is not null; returns null otherwise. 上一篇: Python的内置字典是如何实现的