Cory Klein
Cory Klein

Reputation: 55670

How do you retain trailing newlines when storing command output in a variable?

Is it possible to retain trailing newlines when storing the output of a command in a variable?

$ echo "foo
" # newline appears after foo
foo

$ MYVAR="$(echo "foo
")"
$ echo "${MYVAR}" # newline is stripped
foo
$ 

Upvotes: 1

Views: 209

Answers (1)

chepner
chepner

Reputation: 531165

You can add a sentinel to the end of the stream:

$ my_var=$'foo\n\n'
$ captured=$( echo -n "$my_var"; echo -n "x" )

which you then remove:

$ captured=${captured%x}
$ echo "$captured"

Upvotes: 2

Related Questions