Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Is there a way to make bash not eat newlines in the backtick substitution?

For example:

var=`echo line one && echo line two`
echo $var

line one line two

What I want is

var=`echo line one && echo line two` # plus some magic
echo $var

line one
line two
share|improve this question

2 Answers 2

up vote 28 down vote accepted

It's not an issue with backticks substitution, but with echo; you have to quote the variable to get the control characters working:

$ var=`echo line one && echo line two`
$ echo "$var"
line one
line two
share|improve this answer
So, bash removes newlines while expanding a variable on the command-lien? And that behavior can be disabled by quoting the variable? –  slowpoison Mar 23 '12 at 1:48
bash performs parameters expansion before executing a command, quoting is necessary to inform bash that you want to print a single string and not 4 words (line, one, line and two). Try: echo a <many spaces> b and echo "a <many spaces> b". Take a look to this answer too. –  cYrus Mar 23 '12 at 2:15

I would have put my small addition in a comment on the answer of cYrus, but I cannot yet comment on answers I think. So I'll duplicate part of cYrus his answer for completeness.

What happens in the first line of your code is that indeed the backticks substitution eats the trailing newlines of the output of the substituted command, as documented. But it does not eat the newline between your two lines.

What happens in the second line of code is that echo is executed with two arguments, the first and the second line. Quoting the expanded variable will fix that: echo "$var" This will preserve the newline between your line one and line two. And echo will add a trailing newline by default so that everything is okay.

Now if you wanted to preserve all trailing newlines in the output of some command substitution, a workaround is to add another line the output, which you can remove after the command substitution, see here .

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.