Why is my Perl in-place script exiting with a zero exit code even though it's failing?

こ雲淡風輕ζ 提交于 2021-02-08 15:19:20

问题


I have a one-liner Perl search and replace that looks roughly like this:

perl -p -i -e 's/foo/bar/' non-existent-file.txt

Because the file doesn't exist (which isn't intentional, but this is part of an automated build script, so I want to protect against that), Perl exits with this error:

Can't open non-existent-file.txt: No such file or directory.

However, the exit code is still zero:

echo $?
0

Am I doing something wrong? Should I be modifying my script, or the way I'm invoking Perl? I was naively assuming that because Perl couldn't find the file, it would exit with a non-zero code.


回答1:


You can force error by dying,

perl -p -i -e 'BEGIN{ -f $ARGV[0] or die"no file" } s/foo/bar/' non-existent-file.txt



回答2:


Because that's not a fatal error. If you use perl -pe'...' file1 file2, it would continue to process file2 even if file1 doesn't exist.

The following causes the issuance of any warning to result in a non-zero exit code.

$ perl -i -pe'
   BEGIN {
      $SIG{__WARN__} = sub {
         ++$error;
         print STDERR $_[0];
      };
    }

    END { $? ||= 1 if $error; }

    s/foo/bar/g;
' file1 file2

This means that file2 will still be processed even if file1 doesn't exist, but the exit code will be non-zero.



来源:https://stackoverflow.com/questions/22192300/why-is-my-perl-in-place-script-exiting-with-a-zero-exit-code-even-though-its-fa

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!