存储具有多个值的bash脚本参数

wan*_*ars 1 bash shell

我希望能够将输入解析为如下所示的bash shell脚本。

myscript.sh --casename obstacle1 --output en --variables v P pResidualTT
Run Code Online (Sandbox Code Playgroud)

到目前为止,我拥有的最好的失败了,因为最后一个参数具有多个值。第一个参数只能有1个值,但是第三个参数可以有大于1的值。是否有办法指定应抓住第三个参数之后直到下一个“-”的所有值?我将假定用户不受约束按照我显示的顺序给出参数。

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
Run Code Online (Sandbox Code Playgroud)

Cha*_*ffy 5

一种常规做法(如果要执行此操作)是关闭多个参数。那是:

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

也就是说,建立调用约定更为常见,因此调用者将在每个以下变量中传递一个-V或自--variable变量,即:

myscript --casename obstacle1 --output en -V=v -V=p -V=pResidualTT
Run Code Online (Sandbox Code Playgroud)

...在这种情况下,您只需要:

case $key in
  -V=*|--variable=*) variables+=( "${1#*=}" );;
  -V|--variable)   variables+=( "$2" ); shift;;
esac
Run Code Online (Sandbox Code Playgroud)