Home > database >  How to get dictionary value to parse variables referenced in value using Bash?
How to get dictionary value to parse variables referenced in value using Bash?

Time:02-06

I have a dictionary that has variable names in the value string. I'm trying to lookup the dictionary value, then parse the result with the actual variable value in the string (not the variable name).

How would I do it?

Example:

asset_symbol='BTC'    
counter_asset_symbol='ETH'

Dictionary entry:

['ct']=https://charts.cointrader.pro/charts.html?coin=$asset_symbol:$counter_asset_symbol

When calling the value I want it to parse $asset_symbol and $counter_asset_symbol" to "BTC" and "ETH"

So in this case I want:

https://charts.cointrader.pro/charts.html?coin=BTC:ETH

Examples of what didn't work:

#!/bin/bash

chart_engines=('ct cg')

# No ''
declare -A search_urls=(
    ['ct']=https://charts.cointrader.pro/charts.html?coin=$asset_symbol:$counter_asset_symbol 
    ['cg']=https://beta.coinigy.com/markets/$exchange_symbol/$asset_symbol/$counter_asset_symbol
)

# With single quotes
declare -A search_urls=(
    ['ct']='https://charts.cointrader.pro/charts.html?coin=$asset_symbol:$counter_asset_symbol' 
    ['cg']='https://beta.coinigy.com/markets/$exchange_symbol/$asset_symbol/$counter_asset_symbol'
)

# With double quotes
declare -A search_urls=(
    ['ct']='https://charts.cointrader.pro/charts.html?coin=$asset_symbol:$counter_asset_symbol' 
    ['cg']='https://beta.coinigy.com/markets/$exchange_symbol/$asset_symbol/$counter_asset_symbol'
)


asset_name='Bitcoin'
asset_symbol='BTC'
counter_asset_name='Ethereum'
counter_asset_symbol='ETH'
exchange_name='Binance'
exchange_symbol="BINA"


open_charts_urls(){
    for i in ${chart_engines[@]}; do
        # Get URL

        #  Dictonary lookup doesn't fill in the variables.
        local charts_url="${search_urls[$i]}"
        echo "$charts_url"

        # Direct reference does.
       # echo "https://beta.coinigy.com/markets/$exchange_symbol/$asset_symbol/$counter_asset_symbol"
       # echo "https://charts.cointrader.pro/charts.html?coin=$asset_symbol:$counter_asset_symbol" 
        # local subs="$charts_url"
        # echo "subs:$subs"

    done
}

open_charts_urls

CodePudding user response:

You are referencing $asset_symbol and $counter_asset_symbol before they are declared. Declare the $search_urls array below the declaration of these symbols. Also, use double quotes for the values within the array. Single quotes will prevent the parameter substitution. See quoting. In your example below the comment # With double quotes you are still using single quotes.

  •  Tags:  
  • Related