On Fri, Apr 15, 2022 at 09:47:11PM -0400, The Wanderer wrote:
> On 2022-04-15 at 20:47, Greg Wooledge wrote:
> > On Sat, Apr 16, 2022 at 08:20:40AM +0800, wilson wrote:
> 
> >> ps -efw |grep $PS |grep -v grep
> 
> > You're also going to exit your script with the exit status from that
> > last grep command.  That's probably not what you want.  If it's not,
> > then an explicit "exit 0" at the end might be a good idea.
> > 
> > Or, as another choice, you might want to exit with the exit status
> > of the *first* grep.  In that case, switching them around would be
> > better:
> > 
> > ps -efw | grep -v grep | grep "$PS"
> 
> This would probably result in undesired behavior. I recognize this
> pattern; for reasons that I don't entirely grasp but which seem somehow
> intuitive to me, invoking ps in any of the ways that I've yet found
> useful and piping the output to grep will result in that grep process -
> with its arguments - being listed in the ps output.
> 
> Because the string you're grepping for is included in that argument
> list, that line will be matched, and so will be printed.
> 
> In order to avoid that, the obvious thing to do is just append ' | grep
> -v grep' to the pipeline, so that the unwanted result line gets stripped
> out. I've used that pattern many times.
> 
> IOW: Having the "cut out any lines that mention the command that got the
> search pattern passed to it" command come last is likely to be a necessity.

Your conclusion is not correct.

foobar | grep b | grep -v c

foobar | grep -v c | grep b

both give the same lines of output.  The difference is that the exit
status of the pipeline is that of the last command in the pipeline.

If you go with the first command, you end up with the exit status of
"grep -v c".  When c is grep, and this filter is being used to suppress
the extra race-conditional output of a "grep" command from the process
list (which may not be there), the resulting exit status will be
unpredictable.

With the second command, the exit status will be 0 (success) if there is
at least one matching "b" in the output, and 1 (failure) if not.

Of course, if you put "exit 0" after it, then it doesn't matter.

Reply via email to