开发者

Trailing newlines get truncated from bash subshell

Bash seems to remove trailing newlines from the output of subshells. For instance:

$ echo "Ne开发者_如何转开发wline: '$(echo $'\n')'"

will produce the output

Newline: ''

Does anyone know a workaround or a way to prevent this truncation from happening?


If all you need is just a newline in a variable:

nl=$'\n'

If you need to retain the newline, you can do this (which you show in your own answer):

f () { echo "hello"; }
output=$(f; echo "x")
output=${output%x}
echo "'$output'"

Resulting in:

'hello
'


After some more experimentation I found a workaround using shell variables. Basically, I make sure that the output does not end in a newline, then I strip off the added text later

output="$(echo $'\n'x )"
output="${output%x}"
echo "Newline: '$output'"

This gives the proper output

Newline: '
'


You can use the -e option to enable interpretation of backslash escapes and do it all with one echo.

$ echo -e "Newline: '\n'"

will produce the output

Newline: '
'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜