问题
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