How to check that a parameter was supplied to a bash script

Bash

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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 - Bash

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

Solution 3 - Bash

if (( "$#" != 1 )) 
then
    echo "Usage Info:…"
exit 1
fi

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnode ninjaView Question on Stackoverflow
Solution 1 - BashAdam ZalcmanView Answer on Stackoverflow
Solution 2 - Bashh7rView Answer on Stackoverflow
Solution 3 - Bashjaypal singhView Answer on Stackoverflow