newguy newguy - 1 year ago 57
Perl Question

perl - Why exit code 0 if error file not found, can I make it code 1?

I have a several logical AND commands and in the middle is a perl command that edits a file in-place.

echo before && \
perl -pe 's/foo/bar/g' -i qux && \
echo after

If the file does not exist perl will die with "Can't open qux: No such file or directory." But the error code is 0. That is a problem because I don't want the command to continue. In other words 'after' shouldn't print if the file doesn't exist. Why is that happening and how can I stop it?

Answer Source

You might use perl -pe ... < file instead of perl -pe ... file. In this case the shell will already complain if the file does not exist without even invoking perl. But this can not be used together with the -i switch.

Or since you want to use the -i switch you might check that the file is writable before using it. Not that this checks for qux being both file and writable because being only one of these is not enough (maybe one needs to check for readable too).

[ -f qux ] && [ -w qux ] && perl -pe ... -i qux