Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

bash

shell

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.

like image 367
ederlf Avatar asked Mar 20 '13 13:03

ederlf


People also ask

How do I add options to a bash script?

The ability to process options entered at the command line can be added to the Bash script using the while command in conjunction with the getops and case commands. The getops command reads any and all options specified at the command line and creates a list of those options.

What does %% do in Bash?

In your case ## and %% are operators that extract part of the string. ## deletes longest match of defined substring starting at the start of given string. %% does the same, except it starts from back of the string.


Video Answer


1 Answers

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
like image 94
chepner Avatar answered Oct 26 '22 19:10

chepner