Bash – observing different behaviour of echo

bashechoquoting

I observed the below behavior of echo

#!/bin/bash

x=" hello"

echo $x
echo "$x"

Now when I run the above code I get

ronnie@ronnie:~$ bash test.sh
hello
 hello
ronnie@ronnie:~$

So, can someone explain to me why whitespace in first case is not present in output and also points me to the documentation where this behavior is defined.

Best Answer

It is not the echo behavior. It is a bash behavior. When you use echo $x form the bash get the following command to process (treat as space):

echo␣␣hello

Then this command is tokenized and bash get two tokens: echo and hello thus the output is just hello

When you use the echo "$x" form then the bash has the following at the input of tokenizer:

echo␣"␣hello"

thus it has two tokens echo and ␣hello, so the output is different.

Related Question