1

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
$ 
4

1 に答える 1

2

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"
于 2013-03-06T19:46:01.487 に答える