Home > Net >  Store the results of grep -q and use them later iff they return true in a conditional statement cont
Store the results of grep -q and use them later iff they return true in a conditional statement cont

Time:12-01

I'm writing a style-checking script that:

  • looks for some abuse of style using grep
  • prints a message and the offending lines IF they are found
  • otherwise, prints nothing

I'm currently using

if (grep -Erq 'break;|continue' *) then 
    echo && echo "found breaks and/or continues:"
    grep -Ern 'break;|continue' *
    else echo "no breaks or continues found."
fi

Is there a way to store the result of the first grep (the one in the if conditional with the -q flag) to use later (between the echo statements), or do I have to do the search twice if I want to print out the intermediate echo messages? I understand there are simple workarounds to this particular problem; this is a smaller example of something I want to do at-scale.

CodePudding user response:

You could use:

grep -ERn 'break;|continue' * && {
    echo "^-- Found breaks or continues."
    exit  # or return, if you put this code in a function.
}

echo "No breaks or continues found."

CodePudding user response:

You can store the grep result in a variable, then use it (thanks @CharlesDuffy for rectifying my comment):

if offending=$(grep -Ern 'break;|continue' *)
then
    printf '\n%s\n%s\n' 'found breaks and/or continues:' "$offending"
else
    echo 'No breaks or continues found.'
fi
  • Related