我想在bash中使用getopts来处理命令行参数。 其中一个要求是处理任意数量的选项参数(不使用引号)。
第一个例子(只抓取第一个参数)
madcap:~/projects$ ./getoptz.sh -sabc -s was triggered Argument: a
第二个例子(我希望它的行为是这样的,但不需要引用“
madcap:~/projects$ ./getoptz.sh -s "abc" -s was triggered Argument: abc
有没有办法做到这一点?
这里是我现在的代码:
#!/bin/bash while getopts ":s:" opt; do case $opt in s) echo "-s was triggered" >&2 args="$OPTARG" echo "Argument: $args" ;; \?) echo "Invalid option: -$OPTARG" >&2 ;; :) echo "Option -$OPTARG requires an argument." >&2 exit 1 ;; esac done
我想你想要的是从一个单一的选项获取值列表。 为此,您可以根据需要多次重复该选项,并将其参数添加到数组中。
#!/bin/bash while getopts "m:" opt; do case $opt in m) multi+=("$OPTARG");; #... esac done shift $((OPTIND -1)) echo "The first value of the array 'multi' is '$multi'" echo "The whole list of values is '${multi[@]}'" echo "Or:" for val in "${multi[@]}"; do echo " - $val" done
输出将是:
$ /tmp/t The first value of the array 'multi' is '' The whole list of values is '' Or: $ /tmp/t -m "one arg with spaces" The first value of the array 'multi' is 'one arg with spaces' The whole list of values is 'one arg with spaces' Or: - one arg with spaces $ /tmp/t -m one -m "second argument" -m three The first value of the array 'multi' is 'one' The whole list of values is 'one second argument three' Or: - one - second argument - three
您可以自己分析命令行参数,但getopts
命令不能配置为将多个参数识别为单个选项。 fedorqui的建议是一个很好的选择。
以下是自己解析选项的一种方法:
while [[ "$*" ]]; do if [[ $1 = "-s" ]]; then # -s takes three arguments args="$2 $3 $4" echo "-s got $args" shift 4 fi done