Linux + exit status from Perl one-liner code

kshlinuxperl

I use Perl one-liners in my ksh scripts.

Sometimes it's necessary to get an exit status from the Perl one-liner in order to verify if the Perl one-liner succeeded or not.

For example, I need to verify if the "print" in the Perl one-liner code succeeded or not.

But Perl will exit with status 0 in both cases even if Perl does not match the words "AAA and BBB".

Maybe by changing my code I can get exit status 0 when Perl matches successfully. And get exit status 1 when Perl does not match the words "AAA and BBB".

Is this possible?

more file
AAA BBB


perl -ne '/AAA/ && /BBB/ && print' file
AAA BBB

echo $?
0

 

more file1
ZZZ

perl -ne '/AAA/ && /BBB/ && print' file1
echo $?
 0

Best Answer

Count matching lines and set exit code based on it in an END{...} block:

perl -ne '/AAA/ && /BBB/ && print && $MATCH++; END{exit 1 unless $MATCH>0}' file
Related Topic