在将变量的输出存储在变量中时,是否可以保留尾随换行符?
$ echo "foo
" # newline appears after foo
foo
$ MYVAR="$(echo "foo
")"
$ echo "${MYVAR}" # newline is stripped
foo
$
答案 0 :(得分:2)
您可以在流的末尾添加一个标记:
$ my_var=$'foo\n\n'
$ captured=$( echo -n "$my_var"; echo -n "x" )
然后删除:
$ captured=${captured%x}
$ echo "$captured"