【问题标题】:How do I suppress or remove a newline at the end of Bash command substitution?如何在 Bash 命令替换结束时禁止或删除换行符?
【发布时间】: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

【问题讨论】:

    标签: string bash output


    【解决方案1】:

    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
    • 不是在 Mac 上。是的,不捕获:$() 只捕获标准输出,而不是标准错误,除非您明确重定向
    • 所以python --version 转到stderr 而不是stdout?知道为什么吗?例如。 echo "$(python --version 2>&1) in $(which python)" 有效,因为 which python 进入标准输出,对吗?
    • “为什么”在这里解决:stackoverflow.com/q/26028416/7552。测试程序的结果:which python 2>/dev/nullwhich python >/dev/null 看看其中一个是否没有输出。
    【解决方案2】:

    这里的问题是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''`。
    • @raxacoricofallapatorius 您使用的是哪个版本的 bash?当它提到它需要 Bash 4+ 时,请参阅链接的问题。一种解决方法是改用python --version 2>&1 | tr -d '\n'
    • @fedorqui: 3.2.57(1)-release (x86_64-apple-darwin15)。
    • @raxacoricofallapatorius 然后,正如我所说,使用2>&1 | 而不是|&
    • 当标准错误首先正确复制到标准输出时,不需要修剪换行符。 echo "$(python --version 2>&1) and more text".
    猜你喜欢
    • 2013-02-17
    • 1970-01-01
    • 2013-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多