如何从Bash中的返回码号中提取位

时间:2011-07-08 15:01:21

标签: python bash pylint

我正在使用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(3)并测试null以查看是否发出了致命消息或错误消息。我的问题很简单: bash语法。输入是$ ?, ouptut又是$? (例如使用测试程序)。谢谢!

7 个答案:

答案 0 :(得分:3)

在Bash中你可以使用双括号:

#fatal error
errorcode=7
(( res = errorcode & 3 ))
[[ $res != 0 ]] && echo "Fatal Error"

答案 1 :(得分:2)

Bash支持按位operators ...

$ let "x = 5>>1"
$ echo $x
2
$ let "x = 5 & 4"
$ echo $x
4

答案 2 :(得分:2)

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

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

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

答案 3 :(得分:2)

知道了!

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

谢谢!

答案 4 :(得分: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对象中获得外部命令的返回码。

答案 5 :(得分:1)

要在设置了errexit的脚本中嵌入这样的内容,您可以使用如下表单:

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

灵感来自David's commentthis answer

您可以将pylint blah blah替换为python -c "exit(4+8+16)"

来戳戳它

答案 6 :(得分:0)

使用(可能是次优的)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