Ask Ubuntu is a question and answer site for Ubuntu users and developers. 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

If I have the file input.txt containing:


Then executing the bash command echo $(cat input.txt) will output this:

hello world !

Why and how can I fix it to output exactly what is in the file how it is in the file?

share|improve this question
up vote 17 down vote accepted

If you use

echo "$(cat input.txt)"

it will work correctly.

Probably the input of echo is separated by newlines, and it will handle it as separate commands, so the result will be without newlines.

share|improve this answer
Nice! So what's the difference (if any) between $( ) and backticks? (Sorry if this is too tangential) – Chan-Ho Suh Apr 14 '12 at 2:49
They are equivalent, except for the fact that $(...) is easier to nest. In both cases, if you don't quote the result it will be tokenised into multiple arguments on white space. – James Henstridge Apr 14 '12 at 2:56
But the final newline character is omitted, even in double quotes. In contrast, Perl's backtick operator expands to the entire output of the command, including all newlines. – Keith Thompson Apr 14 '12 at 8:22
@KeithThompson yes, command substitution removes all trailing newlines from the output. That has the advantage of e.g. echo "$(date) something" stripping away the trailing newline from date's output, making that echo output the date and "something" on the same line. If you need to store a file or command output "as is", use mapfile (help mapfile), read -rd '' or a while read-loop. – geirha Apr 14 '12 at 8:26
Thanks everyone :-) I learned something from every comment here! – Chan-Ho Suh Apr 16 '12 at 7:13

Quoted from bash manual page, section Command Substitution:

Embedded newlines are not deleted, but they may be removed during word splitting.

A little further, same section :

If the substitution appears within double quotes, word splitting and pathname expansion are not performed on the results.

That's why echo "$(cat /etc/passwd)" works

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.