1

In this test I'm expecting it to print "var1 is 999".

user@penguin:~$ for num in {1..3}; do export var$num=9999 ; echo var$num is $var$num ; done
var1 is 1
var2 is 2
var3 is 3

user@penguin:~$ echo $var1 $var2 $var3
9999 9999 9999

This prints the PID instead of the variabled named by the two variable names.

user@penguin:~$ for num in {1..3}; do export var$num=9999 ; echo var$num is $$var$num ; done
var1 is 316var1
var2 is 316var2
var3 is 316var3
1

1 Answer 1

3

In your output example you have $$var$num instead of $var$num which you have above. Seems like a typo but $$ is a special parameter that expands to the PID of the shell/subshell it's being executed from.


What you are looking for however is indirect parameter expansion:

for num in {1..3}; do 
    export "var$num"=9999
    varname="var$num"
    echo "var$num is ${!varname}"
done

If there is no requirement to export you could use an array like so:

declare -a array
for ((i=0;i<3;i++)); do 
    array[$i]=9999    
    echo "array[$i] = ${array[$i]}"
done

array[0]=9999 will set the array element index 0 to 9999
${array[0]} will reference the array element with index 0
etc.

4
  • Thanks! that works. I've been struggling with this for hours. Commented Nov 13, 2024 at 1:04
  • You're welcome. Out of curiosity is it a requirement to export these variables? Commented Nov 13, 2024 at 1:06
  • I think it is, but I'm not sure the final form will require it. I'm chaining several commands together, each command gathers a piece of info and sets a variable. In the end all the variables are printed. Commented Nov 13, 2024 at 1:33
  • @DanLarrabee if it's not required to export them it would probably be better to use an array instead. Commented Nov 13, 2024 at 2:18

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.