Storing bash script argument with multiple values

2019-02-27 16:49发布

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

标签: bash shell
1条回答
Rolldiameter
2楼-- · 2019-02-27 17:43

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
查看更多
登录 后发表回答