How to verify that a parameter has been provided in a bash script

I just want to check if one parameter was provided in my bash script or not.

I found this one , but all the solutions seem unnecessarily complicated.

What a simple solution to this simple problem makes sense for a beginner?

+49
bash
Jan 23 '12 at 8:21
source share
3 answers

Use $# , which is equal to the number of arguments provided, for example:

 if [ "$#" -ne 1 ] then echo "Usage: ..." exit 1 fi 

Caution: note that inside the function this will be equal to the number of arguments passed to the function, not the script.

EDIT: As SiegeX pointed out in bash, you can also use arithmetic expressions in (( ... )) . This can be used as follows:

 if (( $# != 1 )) then echo "Usage: ..." exit 1 fi 
+69
Jan 23 '12 at 8:23
source share

The decision made checks whether the parameters specified by testing the counter of the specified parameters are set. If this is not a desired check, that is, if you want to check whether a specific parameter has been set, the following:

 for i in "$@" ; do if [[ $i == "check parameter" ]] ; then echo "Is set!" break fi done 

Or, more compactly,

 for i in "$@" ; do [[ $i == "check argument" ]] && echo "Is set!" && break ; done 
+12
Feb 01 '15 at 13:16
source share
 if (( "$#" != 1 )) then echo "Usage Info:…" exit 1 fi 
+11
Jan 23 '12 at 8:29
source share



All Articles