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

您可以在流的末尾添加一个哨兵:

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

然后删除:

$ captured=${captured%x}
$ echo "$captured"
于 2013-03-06T19:46:01.487 回答