0

Running in some trouble using a variable with a number..

This works;

sourceid_2="blah"
echo $sourceid_2

But this doesnt work;

sourceid_2="blah"
i=2
echo $sourceid_$i

Any ideas how to fix this? I tried without the underscore.. but that didn't help.

My end goal is to do something with the variable in a for i in {2..7} loop.. like this;

for i in {2..7}
do
echo $sourceid_$i
done
Alex van Es
  • 103
  • 1
  • 4

2 Answers2

5

echo $sourceid_$i expands two separate variables: $sourceid_ and $i. The simpliest way to do what you're trying to do is with an indirect reference:

sourceid_2="blah"
i=2
var=sourceid_$i
echo "${!var}"

But as @dave_thompson_085 pointed out, arrays are usually a better way to do this sort of thing:

declare -a sourceid
sourceid[2]="blah"
i=2
echo "${sourceid[i]}"

Note that arrays are a bash extension, and not available in more basic shells.

3

Your problem is not a name containing a number, which works fine, but a name containing a variable. You can use eval (which is hard to get right and easy to screw up) or indirection like x=source_$i; echo "${!x}" in which case this is a dupe of bash array with variable in the name which SX already put automatically in the related list for you to look at.

But if you want several related variables accessed by number, even better is to use an array. That's exactly what arrays are designed to do, making them more convenient and safer. To learn about arrays in bash, see the section of the bash manual about arrays, on your system or on the web here