Incorrect perl command line error value in $?

I use the perl command line to do inplace replacements in a file. This is the code: (pay attention to root perm with sudo)

sudo perl -i -pe "s/foo/bar/" config.txt 

If it succeeds, "echo $?" return 0. Now I am making the file unwritten even for root using chattr as follows:

 sudo chattr +i config.txt 

I run the same perl command and it fails with this error:

Cannot delete config.txt file: operation not allowed, skipping file.

This is normal. However, 'echo $?' in this case, it still returns 0. Why is this so? Should it return a non-zero value indicating an error?

+6
source share
1 answer

The problem is that Perl does not return with non-zero exit status for this condition ( sudo passes the exit status of the command it gave), which is a little annoying. You can solve this problem by learning that the line reading cycle is never entered if the file cannot be renamed and process it using the flag:

 sudo perl -i -ne 's/foo/bar/; print; $wrk = 1; }{ $wrk or exit 1' config.txt 

The Ekimos greeting (or butterfly) "operator" }{ introduces an END block in a sense; what happens after it is executed when the lines of reading the loop from the file have ended. How this works is described here .

The caveat is that it will also report an error if config.txt empty. In short, if a slightly hacky way is to use the special string counter variable $. for the same purpose:

 sudo perl -i -ne 's/foo/bar/; print; }{ $. or exit 1' config.txt 
+2
source

Source: https://habr.com/ru/post/986907/


All Articles