【发布时间】:2015-11-03 16:33:46
【问题描述】:
如何抑制或删除 Bash command substitution 末尾的换行符?
例如,我有
echo "$(python --version) and more text"
如何获得
Python 2.7.10 and more text
而不是
Python 2.7.10
and more text
【问题讨论】:
如何抑制或删除 Bash command substitution 末尾的换行符?
例如,我有
echo "$(python --version) and more text"
如何获得
Python 2.7.10 and more text
而不是
Python 2.7.10
and more text
【问题讨论】:
bash command 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
【讨论】:
brew install python。
$() 只捕获标准输出,而不是标准错误,除非您明确重定向
python --version 转到stderr 而不是stdout?知道为什么吗?例如。 echo "$(python --version 2>&1) in $(which python)" 有效,因为 which python 进入标准输出,对吗?
which python 2>/dev/null 或 which python >/dev/null 看看其中一个是否没有输出。
这里的问题是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' using |&:
echo "$(python --version |& tr -d '\n') and more text"
【讨论】:
-bash: command substitution: line 1: syntax error near unexpected token &'` 和 -bash: command substitution: line 1: python --version |& tr -d '\n''`。
python --version 2>&1 | tr -d '\n'。
2>&1 | 而不是|&。
echo "$(python --version 2>&1) and more text".