1

Is it possible to define variable that is called for example machine1 as machine$counter ( while counter=1 ) ?

For example, I created the /tmp/config.txt file and set the machine1 as array:

 $ more /tmp/config.txt
 machine1=( linux_server critical 1.1.1.1 )
 machine2=( linux_server critical 1.1.1.2 )
 .
 .

Then I created the following simple script to read the /tmp/config.txt. And I try to print the machine array as the following:

 $ more read.config.bash
 #!/bin/bash

 source /tmp/config.txt
 counter=1
 echo ${machine$counter[0]}
 echo ${machine$counter[1]}
 echo ${machine$counter[2]}
 .
 .

But when I run the script, I get:

$ ./read.config.bash
./read.config.bash: line 6: ${machine$counter[0]}: bad substitution
./read.config.bash: line 7: ${machine$counter[1]}: bad substitution
./read.config.bash: line 8: ${machine$counter[2]}: bad substitution

What is the solution for this problem ?

1

Use the eval command.

eval "echo \${machine${counter[0]}}"

Notice that the first $ is escaped so that it isn't evaluated until eval processes the string.

The way this works is that eval executes a command the same as if you had typed it at the command prompt. The difference is that the command that is executed can be constructed programmatically.

So in your scenario, when eval runs on the command, the command it is actually executing looks like this: echo ${machineBLAH}. The inner variable substitution has already been performed separately by the shell before eval runs.

For more information, see this other post: What is the "eval" command in bash?.

1

You can avoid to use eval

source /tmp/config.txt
counter=1
line0="machine$counter[0]"
echo ${!line}

And much better to call echo via loop

for counter in 1 2 3
do
    line="machine$counter[@]"
    for element in "${!line}"
    do
        echo $element
    done
done
  • This works only in bash. In my testing, this didn't work in zsh, ksh, or tcsh. It's still good to know, though. – Sildoreth May 18 '15 at 18:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.