如何在perl脚本中忽略shell命令的退出状态

时间:2012-09-03 06:21:09

标签: perl exit-code filehandler exitstatus

我有以下代码,其中我使用一个命令,用作打开文件的输入。

当我的命令$ cmd给出非零退出状态时,我的脚本退出。我希望它仍然继续并在脚本中完成其余的事情

$cmd = 'ps -u psharma';
open( my $fh, "-|",$cmd ) || die( "$cmd failed: $!" );
my @lines = <$fh>;
close($fh) || die $! ? "Close for $cmd failed: $!" : "Exit status $? from command $cmd";

4 个答案:

答案 0 :(得分:1)

尝试使用Carp警告您没有成功退出,而不是使用die。它仍将继续剧本。

carp ("Did not exit command successfully!\n") if (! close ($fh) );

答案 1 :(得分:0)

如果这是整个脚本,那么如果cmd的执行返回非零,它将在最后一行终止。 如果你想继续执行超出此代码的执行,那么你不应该在最后一行删除die吗?

答案 2 :(得分:0)

You can wrap everything in an eval block and check the "magic variable" $@,如下:

use strict; #always
use warnings; #always

my $cmd = 'ps -u psharma';

my $fh; #defining outside the scope of the eval block
my @lines; #ditto

eval {
    open $fh, "-|", $cmd 
        or die "$cmd failed: $!";

    @lines = <$fh>;
    close $fh
        or die $!
               ? "Close for $cmd failed: $!"
               : "Exit status $? from command $cmd";
}

if($@) {

    warn "Something bad happened: $@\n";
}
#If you made it here with no warning, then everything's okay.

您还可以查看Try::Tiny,其中包含基本try/catch/finally块。

答案 3 :(得分:0)

close($fh) || die $! ? "Close for $cmd failed: $!" : "Exit status $? from command $cmd";

此代码已检查$!/ $? (错误/ $ cmd退出状态)。所以你可以更深入地移动die

close($fh) || $! 
    ? die "Close for $cmd failed: $!" 
    : warn "Exit status $? from command $cmd";

但是,我认为明确的if在这里可以更具可读性。