Vishal Patial
Vishal Patial

Reputation: 11

reading variable in unix shell script and performing operation

I need to read a variable in shell script and using that variable to perform some operation. For e.g. I am reading variable markets from config and using this variable to find out the value of another variable redis_host_silver_$j

command used :-

for j in `echo $markets | awk -F"," '{ for(i=1; i<=NF; ++i) print $i }'`;
do
    echo $(redis_host_silver_$j);
done

Can anyone help me in this?

Upvotes: 0

Views: 163

Answers (2)

grail
grail

Reputation: 930

I personally would steer away from using a for loop to read data directly from process substitution which may or may not have white spaces in it. And whilst the indirect call may work, I would say that your variable type is wrong and the second variable, redis_host_silver, should actually be an array with the items from the file as indices.

So maybe something like:

IFS="," read -ra items <<<"$markets"

for item in "${items[@]}"
do
    echo "${redis_host_silver[$item]}"
done

If the values from "markets" are numbers, then "item" variable in call to array does not require "$"

Upvotes: 0

Jack
Jack

Reputation: 2625

The error is in the echo $(redis_host_silver_$j); part.

The $() syntax in bash expands what's inside as a command so you're actually trying to execute redis_host_silver_$j

Try:

for j in `echo $markets | awk -F"," '{ for(i=1; i<=NF; ++i) print $i }'`;
do
    echo "redis_host_silver_$j";
done

If redis_host_silver_... is a name of a variable that you want the value of then do this:

for j in `echo $markets | awk -F"," '{ for(i=1; i<=NF; ++i) print $i }'`;
do
    VAR=redis_host_silver_$j; echo ${!VAR};
done

Note the curly brackets

Upvotes: 1

Related Questions