Use getopts.
Here's a demo:
#!/bin/bash
#
# Example of using options and arguments in shell scripts
#
while getopts ab OPTION
do
case $OPTION in
a)
aflag=1
;;
b)
bflag=1
;;
esac
done
# print options
echo "Option a: $aflag"
echo "Option b: $bflag"
# print arguments
echo "Arguments:"
shift $(($OPTIND - 1))
for arg in $*
do
echo $arg
done
Usage:
./print_options.sh -ba
# Option a: 1
# Option b: 1
# Arguments:
./print_options.sh -a
# Option a: 1
# Option b:
# Arguments:
./print_options.sh -ab xx yyy
# Option a: 1
# Option b: 1
# Arguments:
# xx
# yyy
The function throws an error if you use an invalid option:
./print_options.sh -a -c
# ./print_options.sh: illegal option -- c
# Option a: 1
# Option b:
# Arguments:
You could handle invalid options with
while getopts ab OPTION
do
case $OPTION in
a)
aflag=1
;;
b)
bflag=1
bval="$OPTARG"
;;
\?)
exit
;;
esac
done
The getopts utility provides a useful feature: it automatically increments the OPTIND (options index) variable. This allows you to differentiate between command-line options and positional arguments.
Additionally, getopts simplifies the parsing of option arguments. If an option is followed by a colon (:) in the options string, the next command-line token/string is treated as the argument for that option.
#!/bin/bash
#
# Example of using options in scripts
#
while getopts ab: OPTION
do
case $OPTION in
a)
aflag=1
;;
b)
bflag=1
bval="$OPTARG"
;;
esac
done
# print options
echo "Option a: $aflag"
echo "Option b: $bflag"
echo "Option b's argument: $bval"
# print arguments
echo "Arguments:"
shift $(($OPTIND - 1))
for arg in $*
do
echo $arg
done
Test it:
./print_options.sh -a -b "arg for b" xx
# Option a: 1
# Option b: 1
# Option b's argument: arg for b
# Arguments:
# xx
The only limitation is that the order of options and arguments matters; options must precede arguments when using getopts, as demonstrated in the following example:
./print_options.sh -b xx yyy -a
# Option a:
# Option b: 1
# Arguments:
# xx
# yyy
# -a