0

I'd like to change the variable used within a bash loop. I'd like the first iteration to echo "/path/to/lol/hello_foo" and the second "/path/to/lol/hello_bar".

But instead, this is printed:

/path/to/lol/fname_one
/path/to/lol/fname_two

Here's the code:

#!/bin/bash                                                                                                                                                                                                                                                                              

path_data='/path/to/lol'
fname_one='hello_foo'
fname_two='hello_bar'

for count in one two
do
    echo $path_data/fname_$count
done
1
  • shouldn't you for loop say : for count in fname_one fname_two do echo $path_data/$count done Commented Jan 8, 2018 at 2:46

3 Answers 3

2

See "How can I use variable variables (indirect variables, pointers, references) or associative arrays?"

Your script would look something like this,

 #!/bin/bash   

 path_data='/path/to/lol'
 fname_one='hello_foo'
 fname_two='hello_bar'

 for count in one two
 do
   _tmpf="fname_$count"
   echo "$path_data/${!_tmpf}" 
 done

Result:

~]# ./test.sh 
/path/to/lol/hello_foo
/path/to/lol/hello_bar
Sign up to request clarification or add additional context in comments.

Comments

1

You can use indirect variable expansion to do this:

...
fname_var=fname_$count
echo "$path_data/${!fname_var}"    # Quoting variable references is a good idea
...

But it's generally better to use arrays for things like this:

#!/bin/bash

path_data='/path/to/lol'
declare -a fname    # Make fname an array, rather than a plain variable
fname[1]='hello_foo'
fname[2]='hello_bar'

for count in 1 2
do
    echo "$path_data/${fname[count]}"
done

If you need text (not numeric) indexes you can use an associative array (bash v4 only):

#!/bin/bash

path_data='/path/to/lol'
declare -A fname    # Capital -A makes an associaltive array
fname[one]='hello_foo'
fname[two]='hello_bar'

for count in one two
do
    echo "$path_data/${fname[$count]}"
done

Comments

1

You can do this with eval (which is probably outdated compared to some of the other answers)

#!/bin/bash

path_data='/path/to/lol'
fname_one='hello_foo'
fname_two='hello_bar'

for count in one two
do
    varname=fname_$count
    eval "varval=$"$varname
    echo $path_data/$varval
done

As noted by others an array is probably a better solution.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.