如何在 Bash 命令替换结束时禁止或删除换行符?

How do I suppress or remove a newline at the end of Bash command substitution?

如何禁止或删除 Bash command substitution 末尾的换行符?

比如我有

echo "$(python --version) and more text"

如何获得

Python 2.7.10 and more text

而不是

Python 2.7.10
 and more text

这里的问题是 python --version 输出到标准错误,而 "and more text" 输出到标准输出。

所以你唯一要做的就是使用 2 >&1:

将 stderr 重定向到 stdin
printf "%s and more text" "$(python --version 2>&1)"

$ echo "$(python --version 2>&1) and more text"
Python 2.7.10 and more text

请注意,最初我是通过管道传送到 tr -d '\n' :

echo "$(python --version |& tr -d '\n') and more text"

bashcommand substitution syntax already removes trailing newlines。您需要做的就是重定向到标准输出:

$ echo "$(python --version) and more text"
Python 2.7.8
 and more text
$ echo "$(python --version 2>&1) and more text"
Python 2.7.8 and more text