5

我正在使用返回此错误代码的 pylint 实用程序:

Pylint should leave with following status code:

* 0 if everything went fine
* 1 if a fatal message was issued
* 2 if an error message was issued
* 4 if a warning message was issued
* 8 if a refactor message was issued
* 16 if a convention message was issued
* 32 on usage error

status 1 to 16 will be bit-ORed so you can know which different
categories has been issued by analysing pylint output status code

现在我需要确定 Bash 中是否出现了致命或错误消息。怎么做?我想我需要位操作;-)

编辑:我知道我需要按位执行第三 (3) 号并针对 null 进行测试以查看是否发出了致命消息或错误消息。我的问题很简单:用 bash 语法来做。输入是 $?,输出又是 $? (例如使用测试程序)。谢谢!

4

7 回答 7

4

在 Bash 中,您可以使用双括号:

#fatal error
errorcode=7
(( res = errorcode & 3 ))
[[ $res != 0 ]] && echo "Fatal Error"
于 2011-07-08T15:19:44.000 回答
2

Bash 支持位运算...

$ let "x = 5>>1"
$ echo $x
2
$ let "x = 5 & 4"
$ echo $x
4
于 2011-07-08T15:04:54.800 回答
2

如果状态为奇数,且最低有效位为 1,则会发出致命消息。

如果状态的下一个最高有效数字为 1,则会发出错误消息。

所以你要检查最后两位是否都是1;换句话说,检查and您的状态代码的按位是否0b11为 3。

于 2011-07-08T15:05:21.483 回答
2

知道了!

[ $(($NUMBER & 3)) -ne 0 ] && echo Fatal error or error was issued

谢谢!

于 2011-07-08T15:19:03.267 回答
2

要将这样的内容嵌入到带有errexitset 的脚本中,您可以使用如下形式:

#!/bin/bash
set -o errexit
set -o nounset
(
    rc=0;
    pylint args args || rc=$?;
    exit $(( $rc & 35 )) # fatal=1 | error=2 | usage error=32
)

灵感来自大卫的评论这个答案

你可以通过替换来戳pylint blah blahpython -c "exit(4+8+16)"

于 2018-04-18T16:24:41.990 回答
1

bash 中最后执行的命令的返回码以$?.

[/tmp] % touch bar
[/tmp] % ls /tmp/bar 
/tmp/bar
[/tmp] % echo $?
0
[/tmp] % ls /tmp/baaz
ls: /tmp/baaz: No such file or directory
[/tmp] % echo $?
1
[/tmp] % 

如果要从说 python 的subprocess模块调用外部命令,则可以在子进程退出后从 Popen 对象获取外部命令的返回码。

于 2011-07-08T15:08:44.040 回答
1

使用(可能是次优的)bash 算术的东西:

for status in 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
do
    if [ $status = 0 ]
    then echo $status: it worked perfectly
    elsif [ $(( $status & 3 )) != 0 ]
    then echo $status: a fatal or error message was sent
    else echo $status: it sort of worked mostly
    fi
done

输出:

0: it worked perfectly
1: a fatal or error message was sent
2: a fatal or error message was sent
3: a fatal or error message was sent
4: it sort of worked mostly
5: a fatal or error message was sent
6: a fatal or error message was sent
7: a fatal or error message was sent
8: it sort of worked mostly
9: a fatal or error message was sent
10: a fatal or error message was sent
11: a fatal or error message was sent
12: it sort of worked mostly
13: a fatal or error message was sent
14: a fatal or error message was sent
15: a fatal or error message was sent
16: it sort of worked mostly

我强烈怀疑脚本(测试)可以更紧密或更简洁(特别是在elif子句中),但这似乎有效(我需要开始工作)。

pylint ...
status=$?     # Catch exit status before it changes
if [ $status = 0 ]
then echo $status: it worked perfectly
elsif [ $(( $status & 3 )) != 0 ]
then echo $status: a fatal or error message was sent
else echo $status: it sort of worked mostly
fi
于 2011-07-08T15:22:26.953 回答