user2650277
user2650277

Reputation: 6729

Bash not expanding some variables

I am storing some commands in an array.Bellow is a simplified example

#!/bin/bash
test_arr=()
x="mural.png"
for q in 10 12 14; do
  for i in 4 6 8; do
    test_arr+=("$x_$q_$i")
  done
done
echo "${test_arr[@]}"

unset test_arr
for q in 10 12 14; do
  for i in 4 6 8; do
    test_arr+=("$x"_"$q"_"$i")
  done
done
echo "${test_arr[@]}"

Output:

4 6 8 4 6 8 4 6 8
4 6 8 4 6 8 4 6 8 test_stack.png_10_4 test_stack.png_10_6 test_stack.png_10_8 test_stack.png_12_4 test_stack.png_12_6 test_stack.png_12_8 test_stack.png_14_4 test_stack.png_14_6 test_stack.png_14_8

The following gives the correct output

#!/bin/bash
test_arr=()
x="mural.png"
#for q in 10 12 14; do
#  for i in 4 6 8; do
#    test_arr+=("$x_$q_$i")
#  done
#done
#echo "${test_arr[@]}"

unset test_arr
for q in 10 12 14; do
  for i in 4 6 8; do
    test_arr+=("$x"_"$q"_"$i")
  done
done
echo "${test_arr[@]}"

Output:

mural.png_10_4 mural.png_10_6 mural.png_10_8 mural.png_12_4 mural.png_12_6 mural.png_12_8 mural.png_14_4 mural.png_14_6 mural.png_14_8

Why does the variables get expanded when using "$x"_"$q"_"$i" and not "$x_$q_$i" ?

Upvotes: 0

Views: 38

Answers (2)

karakfa
karakfa

Reputation: 67467

you don't need loops; bash can do the expansion for you

$ echo mural.png_{10,12,14}_{4,6,8}

mural.png_10_4 mural.png_10_6 mural.png_10_8 mural....

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798526

"_" is a valid character for variable names.

"${x}_${q}_$i"

Upvotes: 2

Related Questions