Correct way to check for a command line flag in bash

BCS picture BCS · May 20, 2010 · Viewed 36.9k times · Source

In the middle of a script, I want to check if a given flag was passed on the command line. The following does what I want but seems ugly:

if echo $* | grep -e "--flag" -q
then
  echo ">>>> Running with flag"
else
  echo ">>>> Running without flag"
fi

Is there a better way?

Note: I explicitly don't want to list all the flags in a switch/getopt. (In this case any such things would become half or more of the full script. Also the bodies of the if just set a set of vars)

Answer

Dennis Williamson picture Dennis Williamson · May 20, 2010

An alternative to what you're doing:

if [[ $* == *--flag* ]]

See also BashFAQ/035.

Note: This will also match --flags-off since it's a simple substring check.