通过管道传输到 grep 的 python 版本返回代码 1

标签 python linux bash shell

<分区>

我想检查当前版本的 python 是否是我在 bash 脚本中期望的版本。

python --version | grep --quiet 'Python 2.7.12 :: Continuum Analytics'
if [ $? == 0 ]; then
    echo "python version ok"
fi

但是 grep 命令总是返回 1,而不是 0,即使我得到一个很好的匹配,即使使用一个简单的 grep 'Python'。要检查它,echo "${PIPESTATUS[1]}" 返回 1

如果我将一些其他输出通过管道传递给 grep,它会按预期工作,例如:

echo 'Python 2.7.12 :: Continuum Analytics' | grep --quiet 'Python 2.7.12 :: Continuum Analytics'

这正常工作,echo "${PIPESTATUS[1]}" 返回 0

传送到 grep 的 python --version 命令出了什么问题?我们该如何解决?

最佳答案

尝试使用 grep 的 -c, --count 选项;

count=$(python --version 2>&1 | grep -c 'Python 2.7.12 :: Continuum Analytics')
if [ $count == 1 ]; then
    echo "python version ok"
fi

关于通过管道传输到 grep 的 python 版本返回代码 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39980771/

相关文章:

python - 在代理后面使用 MechanicalSoup

python - 子进程和 psutil : how to get a list out of subprocess. check_output?

linux - Kmalloc 对齐

regex - fail2ban 定期在 nginx 中查找 403 请求

java - 在终端中同时执行多个while true java程序

python - pygame pygame.error : Error reading from ICO

python - 我如何通过 scipy/numpy 或 sympy 实现第一类球形 hankel 函数?

linux - @INC XFileSharing 2.5 中的 Perl 错误 : Can't locate XFileConfig. pm

linux - 如何使用for循环检查Linux中的挂载点

bash - 如何通过命令行获取随机的32位十六进制字符串?