if
If you only have a single option to check and it will always be the first option ($1
) then the simplest solution is an if
with a test ([
). For example:
if [ "$1" == "-h" ] ; then
echo "Usage: `basename $0` [-h]"
exit 0
fi
Note that for posix compatibility =
will work as well as ==
.
$1
?The reason the $1
needs to be enclosed in quotes is that if there is no $1
then the shell will try to run if [ == "-h" ]
and fail because ==
has only been given a single argument when it was expecting two:
$ [ == "-h" ]
bash: [: ==: unary operator expected
getopt
or getopts
As suggested by others, if you have more than a single simple option, or need your option to accept an argument, then you should definitely go for the extra complexity of using getopts
.
As a quick reference, I like The 60 second getopts tutorial.†
You may also want to consider the getopt
program instead of the built in shell getopts
. It allows the use of long options, and options after non option arguments (e.g. foo a b c --verbose
rather than just foo -v a b c
). This Stackoverflow answer explains how to use GNU getopt
.
† jeffbyrnes mentioned that the original link died but thankfully the way back machine had archived it.