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 substitutionWhat is the solution for this problem ?
bash + how to define array variable with instance number
linux;shell script;array;variable substitution
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?.