Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if a perl command embedded in a bash script returns true?

Tags:

bash

perl

So, I have a bash script inside of which I'd like to have a conditional which depends on what a perl script returns. The idea behind my code is as follows:

for i in $(ls); do
    if $(perl -e "if (\$i =~ /^.*(bleh|blah|bluh)/) {print 'true';}"); then
       echo $i;
   fi;
done

Currently, this always returns true, and when I tried it with [[]] around the if statement, I got errors. Any ideas anyone?

P.s. I know I can do this with grep, but it's just an example. I'd like to know how to have Bash use Perl output in general

P.p.s I know I can do this in two lines, setting the perl output to a variable and then testing for that variables value, but I'd rather avoid using that extra variable if possible. Seems wasteful.

like image 927
Eli Avatar asked Dec 30 '25 09:12

Eli


1 Answers

If you use exit, you can just use an if directly. E.g.

if perl -e "exit 0 if (successful); exit 1"; then
   echo $i;
fi;

0 is success, non-zero is failure, and 0 is the default if you don't call exit.

like image 79
Matthew Flaschen Avatar answered Jan 02 '26 00:01

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!