7

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.

hevi
  • 2,432
  • 1
  • 32
  • 51

2 Answers2

12

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

M3talM0nk3y
  • 1,382
  • 14
  • 22
  • unfortunately not, I need something like ./script.sh -p 'world' 'uncle' -a 'how' 'are' 'you' – hevi Aug 17 '17 at 21:15
  • @hevi I updated my answer and provided an example which shows how to use the same option multiple times. Perhaps this is what you need to do in order to handle multiple values. – M3talM0nk3y Aug 18 '17 at 00:00
4

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
Vytenis Bivainis
  • 2,308
  • 21
  • 28