87

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

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

What's a simple solution to this simple problem that would make sense to a beginner?

1
  • ^answers from above possible duplicate are similar to the ones posted here including a comment about using the [[ -z ]] test Commented Jan 11, 2016 at 21:53

3 Answers 3

113

Use $# which is equal to the number of arguments supplied, e.g.:

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

Word of caution: Note that inside a function this will equal the number of arguments supplied to the function rather than the script.

EDIT: As pointed out by SiegeX in bash you can also use arithmetic expressions in (( ... )). This can be used like this:

if (( $# != 1 )) then echo "Usage: ..." exit 1 fi 
Sign up to request clarification or add additional context in comments.

3 Comments

since this is bash question I would suggest if (( $# != 1 ))
For a range, a case statement may be more idiomatic. The syntax looks alien to beginners, though. case $# in [123]) ;; *) echo fail >&2; exit 1;; esac
Expressions in [] use <, >, != and == for string comparisons and -lt, -gt, -le, -ge, -ne and -eq for arithmetic comparisons. Expressions in (()) use <, >, != and == for arithmetic comparisons. For more operators see bash manpage.
43

The accepted solution checks whether parameters were set by testing against the count of parameters given. If this is not the desired check, that is, if you want to check instead whether a specific parameter was set, the following would do it:

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 

3 Comments

I'm not sure your method is correct… for example: ./script check parameter will succeed (which is incorrect).
@gniourf_gniourf You are fully right. I edited with a solution that actually does the trick. Unfortunatelly with a loop.
you want it compact, there is this weird: for i do [ "$i" == ... probably just to confuse people tldp
14
if (( "$#" != 1 )) then echo "Usage Info:…" exit 1 fi 

2 Comments

Thanks @SiegeX .. have updated the answer. Out of curiosity, any particular difference I should be aware of?
Only that it supports superior syntax such as == != < > <= >= and it can also do boolean logic inside a single (( )) much like you can do in C

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.