[ILUG-BOM] Using grep 'AND'

Osric Fernandes osric.fernandes at gmail.com
Wed Feb 27 14:48:56 EST 2013


Hi Rony, Rajeev,

On Thu, Feb 28, 2013 at 12:01 AM, Rajeev R. K. <rajeevrk at gmail.com> wrote:
>
> On 27 February 2013 23:40, gnulinuxist at gmail.com <gnulinuxist at gmail.com> wrote:
> >
> > Thanks Rajeev and Binand for your tips. I noticed a '-a' option in the if statement so will this below work?
> >
> > If [grep -q "/home" mtab -a grep -q "/backup" mtab ] then.........
> >
>
> Doubtful, since the square brackets are little more than a shorthand
> for encapsulating the conditional and comparative expression syntax of
> the test command(check man test), and in this case, test would not
> know how to evaluate the expressions. In any case, my earlier point
> about having independent tests still stands from a usability
> standpoint.
>

You can omit the square brackets and use "-a" as:
if grep -q /home /etc/mtab -a grep -q /backup /etc/mtab ; then ...

Furthermore, to avoid invalid matches such as "/home1" or
"/export/home", you can use the "-w" option, if your version of grep
supports it (GNU grep does).

However, I wouldn't recommend:
if [ $( grep -cwE '/(home|backup)' /etc/mtab ) = 2 ]; then ...
as some versions of Linux allow a file system to be mounted multiple
times. So, we would get a false positive if /home is mounted twice,
but /backup is not.

A method that's both concise and readable is:
home_mounted=`grep -w /home /etc/mtab`
backup_mounted=`grep -w /backup /etc/mtab`
if [ "$home_mounted" -a "$backup_mounted" ] ; then ...

Regards,
Osric Xavier Fernandes

PS: Great to have the mailing list back. Good job team!


More information about the Linuxers mailing list