Would describe the following combinations:
script -a -b -c arg -d -e
script -abc arg -de
script -abde -c arg
script -e -d -b -a -c arg
script -c arg -abde
script -c arg -a -b -d -e
#!/usr/bin/sh
while getopts ab flag
do
case $flag in
a) print "a option" ;;
b) print "b option" ;;
esac
done
Try running the previous example with the -a -b and -? options.
#!/usr/bin/sh
while getopts :ab flag
do
case $flag in
a) print "a option" ;;
b) print "b option" ;;
\?) print "INVALID option"
print " usage: $0 [ -a -b ] " ;;
esac
done
#!/usr/bin/sh
while getopts :abc: flag
do
case $flag in
a) print "a option" ;;
b) print "b option" ;;
c) print "c option with argument $OPTARG" ;;
\?) print "INVALID option"
print " usage: $0 [-a] [-b] [-c arg] " ;;
esac
done
#!/usr/bin/sh
while getopts :abc:d: flag
do
case $flag in
a) print "a option" ;;
b) print "b option" ;;
c) print "c option with argument $OPTARG" ;;
d) print "d option with argument $OPTARG" ;;
\?) print "INVALID option"
print " usage: $0 [-a] [-b] [-c arg] [-d arg]" ;;
esac
done
Try running the previous script like this:
$ ./getopts.sh -a -b -c hello -d world happy joy joy
What happened?
#!/usr/bin/sh
while getopts :abc:d: flag
do
case $flag in
a) print "a option" ;;
b) print "b option" ;;
c) print "c option with argument $OPTARG" ;;
d) print "d option with argument $OPTARG" ;;
\?) print "INVALID option"
print " usage: $0 [-a] [-b] [-c arg] [-d arg] arg arg..." ;;
esac
done
shift $((OPTIND - 1 ))
while (( $# > 0 ))
do
print "next arg is $1"
shift
done