繁体   English   中英

Bash。 解析错误 output 而不显示错误

[英]Bash. Parse error output without showing error

我想获取并解析 python (python2) 版本。 这种方式(有效):

python2 -V 2>&1 | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/'

出于某种原因,python2 在其错误 output 上使用 -V 参数显示版本。 因为这什么也没做:

python2 -V | sed 's/.* \([0-9]\).\([0-9]\).*/\1\2/'

所以它需要被重定向2>&1才能被解析(stderr to stdout)。 好的,但是我想避免在启动此命令的用户没有安装 python2 时显示的错误。 对于没有安装 python2 的用户来说,屏幕上所需的 output 什么都不是。 我怎样才能做到这一点? 因为我需要显示的错误 output 来解析版本。

我已经使用 hash 命令在条件if语句之前做了一个解决方案,以了解 python2 命令是否存在......所以我有一个可行的解决方法,可以避免在不存在时启动 python2 命令的可能性。 .但只是好奇。 忘记python2。 让我们假设将 stderr 重定向到 stdout 的任何其他命令。 如果有错误,是否有可能(bash 技巧)解析它的 output 而不显示它?

任何想法?

仅当行以Python 2开头时才打印 output :

python2 -V 2>&1 | sed -n 's/^Python 2\.\([0-9]*\).*/2\1/p'

或者,

command -v python2 >/dev/null && python2 -V 2>&1 | sed ...

在脚本中包含下一行

command python2 >/dev/null 2>&1 || {echo "python2 not installed or in PATH"; exit 1; }

已编辑:将which更改为command

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM