簡體   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