1

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.

list 'r
  • 11
  • 1
  • 1
    `grep -q` _has_ no results except for its exit status; that's the whole point of `-q` – Charles Duffy Nov 30 '21 at 20:50
  • 2
    @Fravadona, please don't use `$?` that way. `if result=$(grep ...); then ...` works just as well, and is less error-prone. – Charles Duffy Nov 30 '21 at 20:50
  • @Fravadona, ...for a longer discussion on the topic, see [Why is testing $? to see if a command succeeded or not an anti-pattern?](https://stackoverflow.com/questions/36313216/why-is-testing-to-see-if-a-command-succeeded-or-not-an-anti-pattern) – Charles Duffy Nov 30 '21 at 20:51
  • Ah! forgot about it ^^ Thanks – Fravadona Nov 30 '21 at 20:51
  • 2
    @list'r, btw, the parens around the `grep` actually make your code slower. If you want to just create a command grouping without the side effect of spawning a subshell, that would be `if { grep -ERn 'break;|continue'; }; then ...`, but there's no reason to have any grouping at all here; `if grep -ERn 'break;||continue'; then` works just fine. – Charles Duffy Nov 30 '21 at 20:55

1 Answers1

0

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."
Luis Lavaire.
  • 599
  • 5
  • 17
  • You should almost certainly `exit 1` if the `grep` matches anything. – William Pursell Nov 30 '21 at 20:51
  • Also, probably `grep ... >&2` – William Pursell Nov 30 '21 at 20:57
  • what is the reasoning behind each of these comments, @WilliamPursell? – list 'r Dec 02 '21 at 04:58
  • @list'r error messages belong on stderr, and a program which fails should return non-zero. A program whose purpose is check conformance with a style guide should succeed if the input matches the proscribed style, and fail if it does not. Remarks about particular violations of the style should be considered error messages. – William Pursell Dec 02 '21 at 13:24