1

I'm on Ubuntu 12.04 with bash 4.2.25(1)-release. If I use

#!/bin/bash
echo -n 'test ' > text;
echo 'test2' >> text;

everything works fine and the output of text is test test2. But if I use

#!/bin/bash
TEST='test ';
echo -n $TEST > text;
echo 'test2' >> text;

the space at the end of $TEST is removed and text contains testtest2.

Why? How can I avoid this?

0

1 Answer 1

3

As ever so often, the answer lies in quoting.

echo -n $TEST > text

This will get expanded to:

echo -n test  > text

Note the two spaces after test. The only arguments echo sees are -n and test. Nothing else. The space gets lost here. To keep it, you need to double-quote $TEST:

echo -n "$TEST" > text

See also: Quotes and escaping on the Bash Hackers wiki.

1
  • 2
    Sure thing! I was just confused because your first example had echo -n 'test' before your edit. Note that it's a good habit to double-quote every variable where you want it substituted. You'll run in fewer issues most of the time, and there are only rare occasions where you'd actually want it expanded by the shell.
    – slhck
    Oct 29, 2013 at 22:02

You must log in to answer this question.

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