Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to handle bash with multiple arguments for multiple options

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.

like image 456
hevi Avatar asked Aug 17 '17 20:08

hevi


2 Answers

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

like image 140
mscheker Avatar answered Nov 15 '22 00:11

mscheker


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
like image 38
Vytenis Bivainis Avatar answered Nov 14 '22 23:11

Vytenis Bivainis