Hacker News new | past | comments | ask | show | jobs | submit login

This is really clever... I usually ended up with adding

  | grep -v grep
like in

  ps auxww | grep banana | grep -v grep



this does tend to play havoc with $? values if you're used to using those to test grep's results.


You can always just reverse the greps.


the simple things in life elude me. holy cow. i learned the "tag a grep -v grep" at the end and never looked into refining it. but just flipping the greps? nope, not once did that ever occur to me. thanks


That's a valid concern, but in this case it won't cause problems -- grep exits with 0 if a line was selected; in the case of `grep -v grep` that means there was a line without "grep", which is what we want.

(Also @thewakalix made a good suggestion to reverse the greps.)


except, your grep -v portion will always return a result so $? will also always return 0. even if your grep banana did not find anything.

the reversing the greps will be my new default behavior


Nope, try it out:

  $ printf 'banana\ngrep banana\n' | grep banana | grep -v grep
  banana
  $ echo $?
  0
  $ printf 'grep banana\n' | grep banana | grep -v grep
  $ echo $?
  1
To clarify my previous comment, `grep -v grep` exits with 0 if there was a line without "grep" in the output of `grep banana`.


In bash, you can get the rc of piped things, the var eludes me while walking..


${PIPESTATUS[@]} for a space delimited list of all exit codes, or replace @ with the position in the pipe chain of the specific command you want.

ps auxwww | grep banana | grep -v grep && echo ${PIPESTATUS[1]}

type of thing


You can also set -o pipefail. The first non-zero exit code is returned if there is one.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: