Skip to content
Advertisement

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.

Advertisement

Answer

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 %sn" "$arg1"
printf "Argument 2 is %sn" "$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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement