Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 609
Andrew Ferrier Avatar asked Mar 05 '14 08:03

Andrew Ferrier


1 Answers

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
like image 163
mpapec Avatar answered Oct 13 '22 18:10

mpapec