amazingjxq
amazingjxq

Reputation: 4677

Strange shell behaviour

Here is a simple bash script:

a="asd"
b="qf"
echo "$a.$b"
echo "$a_$b"

It's output is:

asd.qf
qf

Why the second line is not "asd_qf" but "qf"?

Upvotes: 1

Views: 63

Answers (3)

Kevin Grant
Kevin Grant

Reputation: 5431

The shell has rules about what can go in a variable name, and $a_ is interpreted as the variable named a_ (there is no variable with that name so its value is empty).

You can always add braces to be explicit. In this case, ${a}_$b will clearly identify what the variable name is and the result will be what you expect.

Upvotes: 3

Pascal Cuoq
Pascal Cuoq

Reputation: 80255

Your second echo displays the value of variable $a_ which is unset.

Use echo "${a}_$b"

Upvotes: 3

Mat
Mat

Reputation: 206659

Because you haven't defined a variable named a_. For that second printout to work, use:

echo "${a}_$b"

Upvotes: 4

Related Questions