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
Peter Mortensen
  • 2,318
  • 5
  • 23
  • 24
yael
  • 2,433
  • 5
  • 31
  • 43

1 Answers1

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
Peter Mortensen
  • 2,318
  • 5
  • 23
  • 24
AnFi
  • 6,103
  • 1
  • 14
  • 27
  • 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 02 '13 at 09:58
  • perl -ne 'BEGIN{ ... }; if( .... ) { print; $MATCH++ }; END{ exit 1 unless $MATCH>0 };' – AnFi May 02 '13 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 02 '13 at 11:22
  • fix `if` statement between BEGIN and END blocks: `if( /(^|\s)\Q$ip\E(\s|$)/ ) { print; $MATCH++};` – AnFi May 02 '13 at 13:08