Thursday, 18 August 2016

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?


Answer



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.


No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...