Anand
Anand

Reputation: 33

How does bash parse quotes in this example?

I am running an example and trying to figure out how the arguments were parsed.

colour1="red"
colour2="light blue"
colour3="dark green"

for X in "$colour1" $colour2" $colour3"
do
    echo $X
done

Note that the weird missing quotes are not a typo. It's just a test example from a blog.

The output I get is

red

light

blue dark green

The output I expected was

red

light

blue

dark green

since colour2 won't be protected by quotes but colour1 and colour3 should be. What is the interpreter doing?

Upvotes: 3

Views: 35

Answers (1)

chepner
chepner

Reputation: 531245

Because $colour2 and "$ colour3" are immediately adjacent, they form a single word before parameter expansion occurs. Here's how the expansion progresses:

  1. You start with $colour2" $colour3"
  2. Parameter expansion turns this into light blue" dark green"
  3. Word-splitting is applied to the result of the expansion on unquoted whitespace. As there is only one unquoted space, the two resulting words are light and blue" dark green".
  4. Finally quote removal is performed, yielding light and blue dark green.

Upvotes: 4

Related Questions