Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Working with conditions based on command output

Tags:

bash

I have the following code:

#!/bin/bash

for f in `find . ! -type d`;
do
        line=`grep -i 'todo' $f | sed 's/^[ \t]*//'`
        if [ $line ]; then
                echo "$f:"
                echo "$line"
        fi
done

but the condition is not working as I would expect it, I need it to only work if something other than an empty string (or nothing) is returned by the command.

like image 313
UnkwnTech Avatar asked Jan 26 '26 11:01

UnkwnTech


1 Answers

As Alberto pointed out, it's common to use -n to check to see if a string has a non-zero length, but in the case where the string may be empty or contain only whitespace, you'll want to quote the variable:

if [ -n "$line" ] # ...

Similarly, you can check to see if it has a zero length with -z:

if [ -z "$line" ] # ...

Negation is also supported when it makes more sense:

if [ ! -z "$line" ] # ...

Edit: And since you're using bash, you can actually use some other nice features such as:

  1. Double brackets (e.g. [[ expr ]]), and
  2. Regular expressions (e.g. [[ cat =~ ca[bat] ]])

See the conditional constructs section in man bash for more information.

like image 140
Kaleb Pederson Avatar answered Jan 28 '26 18:01

Kaleb Pederson



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!