Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I am a bash beginner and 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.

share|improve this question
up vote 5 down vote accepted

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.

share|improve this answer
I think you misinterpreted my question. what I am asking is why my leading white space is trimmed/lost in the first case. – ronnie Oct 16 '12 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 Oct 16 '12 at 12:47
I will rewrite the answer to reflect these changes – Serge Oct 16 '12 at 12:50
@ronnie In the bash manual, read the section on shell expansions. The tokenization where whitespace becomes separators is word splitting. – Gilles Oct 16 '12 at 13:00
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 Oct 16 '12 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.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.