繁体   English   中英

如何使用多个选项的多个参数处理bash

[英]how to handle bash with multiple arguments for multiple options

我只需要使用bash从poloniex rest客户端下载带有多个选项的图表数据。 我尝试了getopts,但实际上找不到一种使用带有多个参数的多重选项的方法。

这是我想要实现的

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

有我需要调用cxp 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}

好吧,我正在明确写出我的最终目标,可能是当今许多其他人正在寻找的目标。

这样的事情对您有用吗?

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

然后,您可以像这样调用脚本:

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

上面的输出将是:

Argument 1 is hello
Argument 2 is world

更新

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

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

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

./script.sh -c USD -c CAD

输出将是:

USD
CAD

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

您可以将./getdata.sh "currency1 currency2" "period1 period2"

getdata.sh内容:

c=$1
p=$2

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM