在perl中,检测shell脚本返回值

使用perl调用外名命令有很多方法,这里就不详细讲解。

如有shell脚本a.sh

#!/bin/bash

echo "script out put"

exit 2

有perl脚本test.pl调用a.sh

#!/bin/perl -w

$output = qx(/usr/local/a.sh);

$exitcode = $?;

print "output = " . $output;

print "exitcode = " . $exitcode;

执行此perl脚本./test.pl

你会发现输出的内容为

output = script out put

exitcode = 512

明显就不是你所期望的结果。输出应该是

 output = script out put

exitcode = 2

这才是我们期待的。

原因是,perl内部$?的返回值,会将shell的值乘以8,我们给他除以8,便可以解决。

#!/bin/perl -w

$output = qx(/usr/local/a.sh);

$exitcode = $? >>8;

print "output = " . $output;

print "exitcode = " . $exitcode;

再次运行脚本你会发现OK了。

原文地址:https://www.cnblogs.com/agostop/p/2431548.html