4 ms·
This is really clever... I usually ended up with adding | grep -v grep like in ps auxww | grep banana | grep -v grep
by sandreas 5y ago
This is really clever... I usually ended up with adding
| grep -v grep
like in
ps auxww | grep banana | grep -v grep
- dylan604 5y agothis does tend to play havoc with $? values if you're used to using those to test grep's results.
- thewakalix 5y agoYou can always just reverse the greps.
- dylan604 5y agothe 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
- hddqsb 5y agoThat'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.)
- dylan604 5y agoexcept, 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
- hddqsb 5y agoNope, 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`.
- bbarnett 5y agoIn bash, you can get the rc of piped things, the var eludes me while walking..
- dylan604 5y ago${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
- joombaga 5y agoYou can also set -o pipefail. The first non-zero exit code is returned if there is one.