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?
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?
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 bash question I would suggest if (( $# != 1 ))case statement may be more idiomatic. The syntax looks alien to beginners, though. case $# in [123]) ;; *) echo fail >&2; exit 1;; esac[] 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.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 ./script check parameter will succeed (which is incorrect).if (( "$#" != 1 )) then echo "Usage Info:…" exit 1 fi == != < > <= >= and it can also do boolean logic inside a single (( )) much like you can do in C