Zac B
Zac B

Reputation: 4232

How to parse arguments in Bash when switched AND switchless syntax is used?

I've got a bash script that can take arguments in a variety of different formats:

Format 1: myscript.sh value1 value2 [value3 value4] -p -g (no switches/flags on options that have arguments, with switches for options without arguments, which strings correspond to which values is determined partially by the ordering the values are given in and partially by regex-matching on the content of the strings)

Format 2: myscript.sh -s value1 -t value2 [-v value3 -w value4] -p -g (standard options-with-and-without-args format, easily handled by getopts)

Format 3: myscript.sh --longopt value1.... etc. (standard long-options-with-and-without args format).

Here's the stupid part: The syntaxes can be combined: myscript.sh -p value1 value3 --longopt value4 -t value2 -g should be valid, with value1 and value3 being detected by regex or relative position to the other args.

This script is used by dozens of teams in different ways, most of them automated, and everyone wants legacy compatibility with thier usage method to be preserved. I have a massive, ugly, totally manual option parser to handle all three different syntaxes. Every time I need to add a single option and preserve compatibility, I feel like I need a glass of vodka first.

My question:

Is there any utility in Bash/Unix that can parse option syntaxes like this one simply, legibly, and robustly? My alternatives, at this point, are to keep wrestling with the manual parser, or just embed a bunch of Python/optparse code in the script and use that.

Upvotes: 0

Views: 295

Answers (1)

Majid Laissi
Majid Laissi

Reputation: 19788

have you tried getopts ?

while getopts "s:t" OPTION
do
     case $OPTION in
         s)
             VALUE1=$OPTARG
             ;;
                 t)
             VALUE2=$OPTARG
             ;;
             exit
             ;;
         ?)
                #Other stuff
     esac
done     

Upvotes: 2

Related Questions