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?
Check Number of Arguments in Bash We can use the $# command to find the number of values given as arguments to the bash command. For example, we can use this command to prevent the program from executing without the required number of arguments.
To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With