How can I raise an error if grep finds matches but not raise an error if it finds zero matches?

Viewed 19

I've got this script running in a GitHub Action:

INVALID_RESOURCES=$(grep -rnI -E '\"google_bigquery_dataset_iam_member\"|\"google_bigquery_dataset_iam_binding\"|\"google_bigquery_dataset_iam_policy\"' .)
if [ "$(echo "$INVALID_RESOURCES" | wc -l)" -gt 0 ]; then
  echo "$INVALID_RESOURCES"
  exit 1
fi

My aim is to output all the matches and raise an error if grep finds any matches.

Strange thing is that if it doesn't find any matches is still reports 1 line as the following output from my terminal hopefully demonstrates:

➜ INVALID_RESOURCES=$(grep -rnI -E '\"google_bigquery_dataset_iam_member\"|\"google_bigquery_dataset_iam_binding\"|\"google_bigquery_dataset_iam_policy\"' .)

➜ echo $INVALID_RESOURCES


➜ echo $INVALID_RESOURCES | wc -l
       1

As you can see $INVALID_RESOURCES doesn't contain anything (except maybe a newline) but wc -l is still reporting one line.

Can someone explain why this is or, perhaps better, suggest a better way of accomplishing my aim?

0 Answers
Related