how to handle bash with multiple arguments for multiple options

ぃ、小莉子 提交于 2020-03-19 03:52:32

问题


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.

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 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.


回答1:


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




回答2:


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

getdata.sh content:

c=$1
p=$2

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


来源:https://stackoverflow.com/questions/45744569/how-to-handle-bash-with-multiple-arguments-for-multiple-options

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!