1

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

1 Answer 1

2

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
4
  • another question - where to put the "&& $MATCH++; END{exit 1 unless $MATCH>0}'" on ---> perl -ne'BEGIN { $ip = shift(@ARGV); } print if /(^|\s)\Q$ip\E(\s|$)/; ' "$STR" file
    – yael
    May 2, 2013 at 9:58
  • perl -ne 'BEGIN{ ... }; if( .... ) { print; $MATCH++ }; END{ exit 1 unless $MATCH>0 };'
    – AnFi
    May 2, 2013 at 10:12
  • I got error: perl -ne'BEGIN { $ip = shift(@ARGV); }; if (^|\s)\Q$ip\E(\s|$) { print; $MATCH++ }; END{ exit 1 unless $MATCH>0 };' "$STR" file syntax error at -e line 1, near "(^" Substitution replacement not terminated at -e line 1.^C
    – yael
    May 2, 2013 at 11:22
  • fix if statement between BEGIN and END blocks: if( /(^|\s)\Q$ip\E(\s|$)/ ) { print; $MATCH++};
    – AnFi
    May 2, 2013 at 13:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .