Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

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

  • Loading branch information...
commit d4d8c799786afb90824e008c182535bb93e55581 1 parent 3cbe93c
@jneen authored
Showing with 1 addition and 3 deletions.
  1. +1 −3 lib/util.sh
View
4 lib/util.sh
@@ -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

@mattrose

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
Owner

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...?

@Rondom

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
Owner

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
Collaborator
@jneen
Owner

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 "$@" ;}
else
  matches() { grep "$@" 2>&1 >/dev/null ;}
fi
@jneen
Owner

@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.
Something went wrong with that request. Please try again.