perl中如何得到shell脚本的返回值

perl中如何得到shell脚本的返回值

我在perl中调用了shell脚本,想获取shell脚本的返回值,如下:

a.sh:
#!/bin/sh

list=(aa bb cc dd)
if grep "aa"  ${list[@]}
then
     exit 1
fi

b.pl:
#!/usr/bin/perl -w
use strict;

`bash a.sh`;
my $temp=`echo $?`;
print $temp;

运行上面的结果,当a.sh返回0时,b.pl中$temp的值是0;
但是当a.sh返回1时,b.pl中$temp的值是256,为什么?

256 = 1 00000000


QUOTE:
       $CHILD_ERROR
       $?      The status returned by the last pipe close, backtick (``) com-
               mand, successful call to wait() or waitpid(), or from the sys-
               tem() operator.  This is just the 16-bit status word returned
               by the wait() system call (or else is made up to look like it).
               Thus, the exit value of the subprocess is really ("$? >> 8"),
               and "$? & 127" gives which signal, if any, the process died
               from, and "$? & 128" reports whether there was a core dump.
               (Mnemonic: similar to sh and ksh.)

               Additionally, if the "h_errno" variable is supported in C, its
               value is returned via $? if any "gethost*()" function fails.

               If you have installed a signal handler for "SIGCHLD", the value
               of $? will usually be wrong outside that handler

一共是有16bit
高八位是子进程退出值
直接$? >>8 就可以了



[Copy to clipboard] [ - ]
CODE:
my $temp=`echo $?`;

``中的变量是会被替换掉的
所以
`bash a.bash`
执行以后
$? (perl 内置变量) 就是 00000001 00000000
所以替换之后就相当于
my $temp = `echo 256`
结果当然是256了
你想干的事情应该是

[Copy to clipboard] [ - ]
CODE:
my $temp = `echo \$?`;

但是这样还是有问题的
因为你执行了两次外部命令开了两个shell进程,这两个shell进程之间是没有关系的

多谢,大致明白了,那我的脚本这样写没错吧:

a.sh:
#!/bin/sh

list=(aa bb cc dd)
if grep "aa"  ${list[@]}
then
     exit 1
fi

b.pl:
#!/usr/bin/perl -w
use strict;

`bash a.sh`;
my $temp=`echo $?`;
if($temp!=0) {die "test";}

我就是判断一下a.sh的返回值如果非0时,就结束掉perl程序


QUOTE:
原帖由 jiangxue1327 于 2008-8-28 18:12 发表
多谢,大致明白了,那我的脚本这样写没错吧:

#!/usr/bin/perl -w
use strict;

`bash a.sh`;
my $temp=`echo $?`;
if($temp!=0) {die "test";}

my $temp=`echo $?`; #这句何用?

`bash a.sh`;
if($?!=0) {die "test";}
``