1

I used to think that bash expanded something like "$<var>" simply by replacing "textually" $<var> with the content of <var>. However after coming across some examples, I realized that I'm missing something. Consider the following interaction.

1: $ X="A; B"
2: $ printf "%s\n" $X
3: A;
4: B
5: $ printf "%s\n" "A; B"
6: A; B
7: $ printf "%s\n" A; B
8: A
9: B: command not found

As you can see, the output of line 2 is different from that of line 5, so in this case $X expansion is not a simple textual substitution. Even removing the double quotes (line 7) doesn't work.

Can someone explain how exactly these situations are handled by bash?

Jeff Schaller
  • 67,283
  • 35
  • 116
  • 255

1 Answers1

1

Since you have not quoted $X it is subject to word splitting. The command being issued in line 2 is:

printf '%s\n' 'A;' B

Note the ; is escaped by the shell but the whitespace is not. This is different from the command in line 7 which is:

$ printf "%s\n" A; B

Since the ; is not escaped it acts as a command separator meaning the next command is B, which is not a command and therefore you get the command not found error.

Line 5 works as expected because of the double quotes, which need to be used in line 2 as well. They will prevent word splitting. The command you want is:

printf "%s\n" "$X"
jesse_b
  • 37,005