I observed the below behavior of echo


x=" hello"

echo $x
echo "$x"

Now when I run the above code I get

ronnie@ronnie:~$ bash test.sh

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.

2 Answers 2


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):


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:


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

  • I think you misinterpreted my question. what I am asking is why my leading white space is trimmed/lost in the first case.
    – ronnie
    Commented Oct 16, 2012 at 12:42
  • nearly by the same reason. the command is tokenised and then each token is treated. if you like to include the space into the token you also has to escape it with backslash or enclose with quotes: ' whitespace' or \ whitespace
    – Serge
    Commented Oct 16, 2012 at 12:47
  • 1
    I will rewrite the answer to reflect these changes
    – Serge
    Commented Oct 16, 2012 at 12:50
  • 1
    @ronnie In the bash manual, read the section on shell expansions. The tokenization where whitespace becomes separators is word splitting. Commented Oct 16, 2012 at 13:00
  • 1
    Just an editing hint. I find those underscores disorienting, maybe ␣ would look better: “(treat ␣ as spaces): echo␣␣helo”. Wikipedia mentions it as “Unicode also provides some visible characters to stand in for space when necessary – U+2423 | 9251 | Open box | Control Pictures | ␣”.
    – manatwork
    Commented Oct 16, 2012 at 13:08

The reason you see different output is because the echo[1 space]Hello line is syntactically equal to echo[5 spaces]Hello. The whitespace is ignored, and the word 'Hello' is treated as the argument to echo. The first line, in it's simplest form, is much the same as if you had said echo "Hello". In the second line, you have explicitly included a leading space as part of the argument to echo, with echo " Hello".

In the first line, you are passing a 5 character string to echo, and in the second line you are passing a 6 character string to echo.

So, in fact, the behavior of echo is the same in both instances, it's just the string being passed to echo that changes.

You must log in to answer this question.

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