grep -q VS. grep > /dev/null

der.hans PLUGd at LuftHans.com
Wed May 28 23:19:39 MST 2014


Am 28. Mai, 2014 schwätzte Bryan O'Neal so:

moin moin Bryan,

because you're weird :). Or maybe that's Al,
http://www.youtube.com/watch?v=JUQDzj6R3p4 :).

Not every grep supports -q, but I don't know if that's the case for
current releases. GNU grep has supported it for years and years. Looks
like FreeBSD has for at least a few major releases, so also for years and
years.

AIX, Solaris, etc. probably don't, but you should install GNU grep, GNU
date, etc. on those anyway :).

[[ ]] vs [ ] is just for extra emphasis :). Or maybe... [[ ]] is for
compound commands and [ ] is for test. Both use conditional expressions.

The compound command, [[ ]], allows extra operators.

== and != allow glob pattern matching:

$ ( fred=anke; if [[ $fred == *ke ]] ; then echo $fred; fi )
anke
$

$ ( fred=anke; if [ $fred == *ke ] ; then echo $fred; fi )
$

$ ( fred=anke; if [[ $fred == [:alpha:]?ke ]] ; then echo $fred; fi )
anke
$

=~ allows regex pattern matching:

$ ( fred=anke; if [[ $fred == [:alpha:]*ke ]] ; then echo $fred; fi )
anke
$

Hmm, cool. According to bash(1), "If the regular expression is
syntactically incorrect, the conditional expression's return value is 2."

Note that the patterns to be matched must be on the right hand side of the
operator.

Now I need to make time to update my class materials as I just realized
there's a dearth of references to Weird Al :).

ciao,

der.hans

> So I had a coworker ask me why I always do
> echo $foo | grep $bar > /dev/null
> if [[ $? -eq 0]] then; ....
>
> Instead of just using greps quiet option. And I remember their being
> some definite bug with -q and checking return codes but for the life
> of me I can not recall it right now.  Just like I can not recall why I
> use [[ ]] insted of just [ ]. Their was a reason I switched at some
> point but can not recall what it is.
> It could have been somthing  with egrep or using peal regex with grep
> but honestly I can not recall...
>
> Thus I am here to ask you, my fellow bash geeks, what what that reason!
> ---------------------------------------------------
> PLUG-discuss mailing list - PLUG-discuss at lists.phxlinux.org
> To subscribe, unsubscribe, or to change your mail settings:
> http://lists.phxlinux.org/mailman/listinfo/plug-discuss
>

-- 
#  http://www.LuftHans.com/        http://www.LuftHans.com/Classes/
#  "It's not that I'm so smart, it's just that I stay with problems longer."
#  -- Albert Einstein


More information about the PLUG-discuss mailing list