【问题标题】:how to handle bash with multiple arguments for multiple options如何处理具有多个选项的多个参数的bash
【发布时间】:2023-04-07 10:24:02
【问题描述】:

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

这就是我想要实现的目标

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

有我需要为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}

好吧,我正在明确地写下我的最终目标,现在可能还有许多其他人正在寻找它。

【问题讨论】:

    标签: linux bash macos poloniex


    【解决方案1】:

    这样的东西对你有用吗?

    #!/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 retrieving multiple variables from one flag

    【讨论】:

    • 很遗憾没有,我需要类似 ./script.sh -p 'world' 'uncle' -a 'how' 'are' 'you'
    • @hevi 我更新了我的答案并提供了一个示例,该示例显示了如何多次使用相同的选项。为了处理多个值,也许这是您需要做的。
    【解决方案2】:

    你可以打电话 ./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
    

    【讨论】:

    • 不完全是我想要的,但很简单,很好的解决方案,谢谢。
    猜你喜欢
    • 2018-03-05
    • 2017-03-24
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 2021-06-27
    • 1970-01-01
    • 2013-04-17
    • 2018-08-24
    相关资源
    最近更新 更多