如何使用多个选项的多个参数处理bash [英] how to handle bash with multiple arguments for multiple options

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

问题描述

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

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.

这是我要实现的目标

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

具有需要在c x p次调用wget的参数

having the arguments I need to call wget for c x p times

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.

推荐答案

这样对您有用吗?

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

上面的输出将是:

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

输出将是:

USD
CAD

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

这篇关于如何使用多个选项的多个参数处理bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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