fm_user8
fm_user8

Reputation: 438

Combining Grep Checks in Bash Script Condition

I do have egrep (i.e. grep -E) available, and I am sure it is possible, but I spent entirely too much time trying to figure out how to one-line this. awk is also an acceptable alternative to grep.

Anybody care to turn this into a single "until" statement? Both grep queries need to exist in xrandr output, not just one or the other.

while true ; do
    if xrandr | grep -q "primary 720x720+0+0" ; then
        if xrandr | grep -q "connected 512x512+720+0" ; then
            return
        fi
    fi
    ...
done

Upvotes: 0

Views: 72

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295403

grep is the wrong tool for this job. You could use awk:

if xrandr | awk '
    /primary 720x720[+]0[+]0/ { found_a=1 }
    /connected 512x512[+]720[+]0/ { found_b=1 }
    END { if (found_a && found_b) { exit(0) } else { exit(1) } }
'; then
  echo "Yes, found both strings"
else
  echo "No, did not find both strings"
fi

...or you could just do your logic right in the shell:

xrandr_out=$(xrandr)
if [[ $xrandr_out = *"primary 720x720+0+0"* ]] \
&& [[ $xrandr_out = *"connected 512x512+720+0"* ]]; then
  echo "Yes, found both strings"
else
  echo "No, did not find both strings"
fi

Either way, the simple thing to do is to embed the logic in a function:

xrandr_all_good() {
  xrandr | awk '
    /primary 720x720[+]0[+]0/ { found_a=1 }
    /connected 512x512[+]720[+]0/ { found_b=1 }
    END { if (found_a && found_b) { exit(0) } else { exit(1) } }
  '
}

until xrandr_all_good; do
  : "...stuff here..."
done

Upvotes: 3

Related Questions