10

I have this Bash script

for i in 1 2 3
do
    for j in 4 5 6
    do
        echo "hello_$i_$j"
    done
done

but it prints

hello_4
hello_5
hello_6

three times, whereas (you may guess) I want hello_1_4, hello_1_5, etc.

Escaping only the underscore or only the dollar sign does not work. Any ideas?

Thanks!

1

1 Answer 1

16

Add the line: set -u to the top of your code. Then rerun and see what you get.

The error that variable i_ is unbound, meaning not defined anywhere. Now why is bash talking about this variable i_? You did not define it anywhere. Look closely at your echo statement: "hello_$i_$j" the underscore after the $i is being seen as the variable i_ since _ is a valid variable name identifier character.

So to prevent bash from doing so, you need to enclose the variable name in braces {}, like as, echo "Hello_${i}_${j}" The braces prevent the variable name from spilling over and abutting with the _. Note: the braces on variable $j are optional as the " serves the purpose of delimiting.

Not the answer you're looking for? Browse other questions tagged .