0

How can I get cat to add a literal line break after each line? (for echo -e to read it) in bash

root@111[~]# cat names 
Joe Smith
John St. John
Jeff Jefferson
root@111 [~]# var=`cat names`;echo -e $var
Joe Smith John St. John Jeff Jefferson

I want the second command to produce output identical to the first.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
Sam Roberts
  • 379
  • 6
  • 13
  • If you don't use quotes, `$var` gets string-split and glob-expanded, meaning each word in the string is passed to `echo` as a separate argument. So, `Joe` is the first argument, `Smith` is the second, `John` is the third, etc. – Charles Duffy May 13 '15 at 00:24
  • ...in that case, why would you *expect* it to separate `Smith` and `John` in a different way from how it separates `Joe` and `Smith`? – Charles Duffy May 13 '15 at 00:24
  • As such, this isn't a problem with `cat` at all; it's a problem with how you're using `echo`. – Charles Duffy May 13 '15 at 00:24

1 Answers1

1

First, don't use echo -e; it adds no value here, and the POSIX standard for echo explicitly disallows the behavior you're expecting it to provide (a POSIX-compliant echo with XSI extensions will honor backslash escapes without -e; a POSIX-compliant echo without XSI extensions will just echo the literal string -e and still ignore backslash escapes; the GNU implementation that changes its behavior based on whether -e breaks both XSI and baseline versions of the standard).

Second, use quotes:

echo "$var"

...or, better, skip echo altogether in favor of printf:

printf '%s\n' "$var"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441