Browse files

turns out grep has an option to do this. Who knew :)

  • Loading branch information...
1 parent 3cbe93c commit d4d8c799786afb90824e008c182535bb93e55581 @jneen committed Jul 19, 2011
Showing with 1 addition and 3 deletions.
  1. +1 −3 lib/
@@ -11,9 +11,7 @@ exists() {
type "$@" >/dev/null 2>/dev/null
-matches() {
- grep "$@" >/dev/null
+alias matches='grep -q'
pluralize() {
if [ -n "$1" ]; then

7 comments on commit d4d8c79

GNU grep has this option, but nobody uses it because it's marked as non-portable in the man page

   -s, --no-messages
          Suppress error messages about nonexistent or  unreadable  files.
          Portability note: unlike GNU grep, traditional grep did not con-
          form to POSIX.2, because traditional grep lacked a -q option and
          its  -s option behaved like GNU grep's -q option.  Shell scripts
          intended to be portable to traditional grep should avoid both -q
          and -s and should redirect output to /dev/null instead.

jneen replied Jul 20, 2011

Yeah, that's really too bad - thanks for the tip. We're also using a fair amount of non-portable options to netcat. I wonder if there's a fancier way to do feature detection than uname -o...?

I think --version might be the best approach, since it tests the executable in question and not the kernel. If there is no version-switch I think grepping --help might be another option. As a last resort I would go by trial and error i.e. test with simple commands in the beginning.


jneen replied Jul 20, 2011

Having a little experience in browser environments, I think the trial-and-error thing is probably the most reliable (i.e. relies on detecting the actual feature, rather than documentation thereof).


laughinghan replied Jul 20, 2011


jneen replied Jul 20, 2011

does someone want to confirm that this works on BSD/Solaris/etc? I can confirm it chooses grep -q on GNU.

test_grepq() {
  local output="$(echo x | grep -q x)"
  [[ $? == 0 ]] || return 1
  [[ -z "$output" ]] || return 1
  return 0

test_greps() {
  local output="$(echo x | grep -s x)"
  [[ $? == 0 ]] || return 1
  [[ -z "$output" ]] || return 1
  return 0

if test_grepq; then
  matches() { grep -q "$@" ;}
elif test_greps; then
  matches() { grep -s "$@" ;}
  matches() { grep "$@" 2>&1 >/dev/null ;}

jneen replied Jul 20, 2011

@laughinghan, but that would be giving up :). Plus, grep -{q,s} has a safety advantage to redirecting output - since it exits as soon as it finds a match. Oftentimes it is used with tail -f to tell a script "wait until someone writes a log to a particular file that looks like ".

Please sign in to comment.