存储具有多个值的bash脚本参数 [英] Storing bash script argument with multiple values
问题描述
我希望能够将输入解析为如下所示的bash shell脚本.
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
到目前为止,我拥有的最好的失败了,因为最后一个参数具有多个值.第一个参数只能有1个值,但第三个参数可以有大于1的值.是否有办法指定应抓住第三个参数之后直到下一个-"的所有值?我将假设用户不受约束按照我显示的顺序给出参数.
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
推荐答案
一种常规做法(如果要执行 ,则要取消多个参数).那就是:
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
也就是说,建立您的调用约定更为常见,因此调用者将在每个以下变量中传递一个-V
或--variable
参数,即:
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
这篇关于存储具有多个值的bash脚本参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!