How to check that a parameter was supplied to a bash script [duplicate]

Solution 1:

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

Solution 2:

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