How to create a bash script with optional parameters for a flag

bash, shell

Solution

The `getopt` external program allows options to have a single optional argument by adding a double-colon to the option name.

# Based on a longer example in getopt-parse.bash, included with
# getopt
TEMP=$(getopt -o a:: -- "$@")
eval set -- "$TEMP"
while true ; do
   case "$1" in
     -a)
        case "$2" in 
          "") echo "Option a, no argument"; shift 2 ;;
          *) echo "Option a, argument $2"; shift 2;;
        esac ;;
     --) shift; break ;;
     *) echo "Internal error!"; exit 1 ;;
   esac
done

Problem

I'm trying to create a script which will have a flag with optional options. With getopts it's possible to specify a mandatory argument (using a colon) after the flag, but I want to keep it optional. It will be something like this: ``` ./install.sh -a 3 ``` or ``` ./install.sh -a3 ``` where 'a' is the flag and '3' is the optional parameter that follows a. Thanks in advance.

Original source