24

Consider this line:

${libdir}/bin/licenseTool check "${SERIAL}" "${VERSION}" "${PRODUCT}" ${libdir} | grep '^200' >/dev/null

What's the point of looking for the pattern in the output if the result of that is thrown away?

And, if a line like that appears as the last thing in a bash script, is its exit value returned to the script's caller, or ignored? (I'm speculating on whether we can assume this is done for side effects only or returns something to the caller somehow.)

29

Your suspicion is correct; the exit status of the last command of the script will be passed to the calling environment. So the answer is that this script will return an exit status 0 if grep matched someting in the data, exist status 1 if there was no match, and exit status 2 if some error occurred.

27

The point of grepping output that is thrown away is that the writer only wants the return status of grep. He/She only wants to know whether a pattern matched or not. In your case, the last grep checks if the earlier command's output contains any lines start with 200.

In modern POSIX system, you can do it all with grep -q without redirecting to /dev/null:

... | grep -q '^200'

A note that using grep -q has a minor side effect, thanks Stéphane Chazelas for pointing out in his comment. grep -q exits as soon as it find the first match, if licenseTool still writes something after grep exited, it will receive a SIGPIPE.

  • 2
    and grep -q uses less CPU – Skaperen Apr 23 '15 at 11:32
  • 5
    As these things go, grep -q was added relatively recently; lots of scripts still use > /dev/null instead because that was all you had back in the Ice Age (that is, 1995). – zwol Apr 23 '15 at 13:19
  • 3
    Is your first sentence lacking a verb? – A.L Apr 23 '15 at 16:23
  • Another disequivalence between "grep -q" and "grep >/dev/null", from the GNU manpage: "However, if the -q or --quiet or --silent is used and a line is selected, the exit status is 0 even if an error occurred." – Mark Apr 23 '15 at 22:33
  • if the documentation is correct "the exit status is 0 even if an error occurred"... I think -q option does not seem appropriate... because you want it to know about the error by checking the exit status. – Trevor Boyd Smith Apr 24 '15 at 12:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.