如何处理具有多个选项的多个参数的 bash

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45744569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 16:22:56  来源:igfitidea点击:

how to handle bash with multiple arguments for multiple options

linuxbashmacospoloniex

提问by hevi

I need to download chart data from poloniex rest client with multiple options using bash only. I tried getopts but couldn't really find a way to use mutliple options with multiple parameters.

我需要仅使用 bash 从具有多个选项的 poloniex rest 客户端下载图表数据。我尝试了 getopts,但无法真正找到一种使用具有多个参数的多个选项的方法。

here is what I want to achieve

这是我想要实现的目标

./getdata.sh -c currency1 currency2 ... -p period1 period2 ...

having the arguments I need to call wget for c x ptimes

有参数我需要c x p多次调用 wget

for currency in c
    for period in p
        wget https://poloniex.com/public?command=returnChartData&currencyPair=BTC_{$currency}&start=1405699200&end=9999999999&period={$period}

well I am explicitly writing my ultimate goal as probably many others looking for it nowadays.

好吧,我正在明确地写下我的最终目标,就像现在许多其他人正在寻找它一样。

回答by mscheker

Could something like this work for you?

像这样的事情对你有用吗?

#!/bin/bash

while getopts ":a:p:" opt; do
  case $opt in
    a) arg1="$OPTARG"
    ;;
    p) arg2="$OPTARG"
    ;;
    \?) echo "Invalid option -$OPTARG" >&2
    ;;
  esac
done

printf "Argument 1 is %s\n" "$arg1"
printf "Argument 2 is %s\n" "$arg2"

You can then call your script like this:

然后你可以像这样调用你的脚本:

./script.sh -p 'world' -a 'hello'

The output for the above will be:

上述输出将是:

Argument 1 is hello
Argument 2 is world

Update

更新

You can use the same option multiple times. When parsing the argument values, you can then add them to an array.

您可以多次使用相同的选项。解析参数值时,您可以将它们添加到数组中。

#!/bin/bash

while getopts "c:" opt; do
    case $opt in
        c) currs+=("$OPTARG");;
        #...
    esac
done
shift $((OPTIND -1))

for cur in "${currs[@]}"; do
    echo "$cur"
done

You can then call your script as follows:

然后,您可以按如下方式调用您的脚本:

./script.sh -c USD -c CAD

The output will be:

输出将是:

USD
CAD

Reference: BASH: getopts retrieving multiple variables from one flag

参考:BASH:getopts 从一个标志中检索多个变量

回答by Vytenis Bivainis

You can call ./getdata.sh "currency1 currency2" "period1 period2"

你可以打电话 ./getdata.sh "currency1 currency2" "period1 period2"

getdata.shcontent:

getdata.sh内容:

c=
p=

for currency in $c ; do 
  for period in $p ; do
    wget ...$currency...$period...
  done
 done