1

I would like to be able to parse an input to a bash shell script that looks like the following.

myscript.sh --casename obstacle1 --output en --variables v P pResidualTT

The best I have so far fails because the last argument has multiple values. The first arguments should only ever have 1 value, but the third could have anything greater than 1. Is there a way to specify that everything after the third argument up to the next set of "--" should be grabbed? I'm going to assume that a user is not constrained to give the arguments in the order that I have shown.

casename=notset
variables=notset
output_format=notset
while [[ $# -gt 1 ]]
do
    key="$1"
    case $key in
        --casename)
        casename=$2
        shift
        ;;
        --output)
        output_format=$2
        shift
        ;;
        --variables)
        variables="$2"
        shift
        ;;
        *)
        echo configure option \'$1\' not understood!
        echo use ./configure --help to see correct usage!
        exit -1
        break
        ;;

    esac
    shift
done

echo $casename
echo $output_format
echo $variables
2
  • in your example, does --variables have 2 or 3 values? and if the answer is 2, how would you expect the script to differentiate between parameter values (v and P) and non-parameter values (pResidualTT)? how were you planning on referencing the multi-valued parameters later in the script ... loop through an array of values? parse a variable of concatenated values? Commented Sep 19, 2017 at 21:06
  • The third argument would just be dumped into a variable and passed directly to a different script that knows how to parse the individual components of that third argument. Commented Sep 19, 2017 at 21:32

1 Answer 1

7

One conventional practice (if you're going to do this) is to shift multiple arguments off. That is:

variables=( )
case $key in
  --variables)
    while (( "$#" >= 2 )) && ! [[ $2 = --* ]]; do
      variables+=( "$2" )
      shift
    done
    ;;
esac

That said, it's more common to build your calling convention so a caller would pass one -V or --variable argument per following variable -- that is, something like:

myscript --casename obstacle1 --output en -V=v -V=p -V=pResidualTT

...in which case you only need:

case $key in
  -V=*|--variable=*) variables+=( "${1#*=}" );;
  -V|--variable)   variables+=( "$2" ); shift;;
esac
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.