0

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?

4
  • im getting error like below :- + for j in 'echo $markets | awk -F"," '\''{ for(i=1; i<=NF; ++i) print $i }'\''' ++ redis_host_silver_uk test.sh: line 61: redis_host_silver_uk: command not found Commented Feb 17, 2017 at 8:24
  • Try quoting around your echo, like echo "redis_host_silver_$j"; Commented Feb 17, 2017 at 8:29
  • Also if you have the permissions to do so, it would be helpful to edit the original question to add error message Commented Feb 17, 2017 at 8:30
  • eval might be needed... You probably want arrays though... Also $(stuff) will run stuff and replace in the result. (a=1;$(stuff_$a) will run stuff_1) Commented Feb 17, 2017 at 14:07

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

Glad to help. Which method did you use?
Indirect expansion seems like a much better option than eval... (Which is how I would have approached it...)
0

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 "$"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.