2
$ cat temp.txt
hello, world!





$ cat temp.txt | sed -n '1,4p'
hello, world!



$ ret=$(cat temp.txt | sed -n '1,4p')
$ echo "$ret"
hello, world!
$

I am wondering why the $ret variable does not have the empty lines.

Much appreciated for the help.

Clayton Stanley
  • 7,513
  • 9
  • 32
  • 46

2 Answers2

4

From the bash man page (emphasis mine):

Bash performs the expansion by executing command and replacing the command substitution with > the standard output of the command, with any trailing newlines deleted. Embedded newlines are not deleted, but they may be removed during word splitting. The command substitution $(cat file) can be replaced by the equivalent but faster $(< file).

chepner
  • 497,756
  • 71
  • 530
  • 681
-1

The parsing of the echo "$ret" skips whitespace in determining what the actual arguments to echo will be. Play around with things like this to understand better:

x=$(echo '   foo    ')
echo "x${x}x"
echo ${x}
echo "${x}"
twalberg
  • 59,951
  • 11
  • 89
  • 84