使用getopts的多个选项参数(庆典) [英] Multiple option arguments using getopts (bash)

查看:616
本文介绍了使用getopts的多个选项参数(庆典)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过程中使用getopts的在bash命令行参数。其中一个要求是选项参数任意数目的处理(不带引号的使用)。

1的例子(只抓住第一个参数)

 狂妄:〜/项目$ ./getoptz.sh -s A B C
-s被触发
参数:一个

第二个示例(我希望它这样的表现,但无需引用参数

 狂妄:〜/项目$ ./getoptz.sh -sA B C
-s被触发
参数:A B C

有没有办法做到这一点?

这里的code现在我有:

 #!/斌/庆典
而getopts的S:选择;做
    案例$选择在
    S)回声-s触发>和2
       ARGS =$ OPTARG
       呼应之争:的$ args
       ;;
   ?\\)回声无效选项: - $ OPTARG>和2
       ;;
    :)回声选项 - $ OPTARG需要一个说法。 >和2
       1号出口
       ;;
    ESAC
DONE


解决方案

我想你想要的是从一个选项得到值的列表。对于这一点,你可以重复选择,因为需要很多次,并添加它的参数数组。

 #!/斌/庆典而getopts的M选择;做
    案例$选择在
        M)多+ =($ OPTARG);;
        #...
    ESAC
DONE
移$((OPTIND -1))回声的阵列的第一个值多是$多'
回声值的整个列表是$ {多[@]}'回声或者:在VAL$ {多[@]};做
    回声 - $ VAL
DONE

将输出:

  $的/ tmp /吨
该阵列的第一个值多是''
值的整个列表是''
要么:$的/ tmp /吨-m一ARG用空格
阵'多'的第一个值是'一ARG用空格
值的整个列表是一ARG用空格
要么:
  - 一个ARG用空格$的/ tmp /吨-m一个-m第二个参数-m 3
该阵列的第一个值多是一
值的整个列表是一第二个参数三个
要么:
  - 一个
  - 第二个参数
  - 三

I am trying to process command line arguments using getopts in bash. One of the requirements is for the processing of an arbitrary number of option arguments (without the use of quotes).

1st example (only grabs the 1st argument)

madcap:~/projects$ ./getoptz.sh -s a b c
-s was triggered
Argument: a

2nd example (I want it to behave like this but without needing to quote the argument"

madcap:~/projects$ ./getoptz.sh -s "a b c"
-s was triggered
Argument: a b c

Is there a way to do this?

Here's the code I have now:

#!/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

解决方案

I think what you want is to get a list of values from a single option. For that, you can repeat the option as many times as needed, and add it's argument to an array.

#!/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

The output would be:

$ /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的多个选项参数(庆典)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆