Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of input argument in a Bash shell script

Tags:

bash

shell

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?

like image 298
user775187 Avatar asked Jun 26 '11 05:06

user775187


People also ask

How do I see arguments in bash?

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.

How do I check if an argument is empty in bash?

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"


1 Answers

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.

like image 77
phoxis Avatar answered Sep 28 '22 06:09

phoxis