help-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Passing multiple search directories to grep


From: Greg Wooledge
Subject: Re: Passing multiple search directories to grep
Date: Tue, 3 Aug 2021 08:55:23 -0400

On Tue, Aug 03, 2021 at 12:10:21PM +0000, hancooper wrote:
> On Tuesday, August 3, 2021 11:32 AM, Greg Wooledge <greg@wooledge.org> wrote:
> > So, if this command works on your system:
> >
> > grep -rl PATH /tmp /var/tmp
> >
> > then the same command generated using an array expansion will also work.

> Do you understand how grep distinguishes the search pattern from the search 
> directories ?

Yes.  The search pattern is the first argument string (after options
have been processed and removed).  All of the argument strings after
the pattern are files or directories to be read.  If there are no
arguments after the pattern, then standard input is read.

This is made clear by the man page:

SYNOPSIS
       grep [-E|-F] [-c|-l|-q] [-insvx] -e pattern_list
           [-e pattern_list]... [-f pattern_file]... [file...]

       grep [-E|-F] [-c|-l|-q] [-insvx] [-e pattern_list]...
           -f pattern_file [-f pattern_file]... [file...]

       grep [-E|-F] [-c|-l|-q] [-insvx] pattern_list [file...]

In the absence of -e and -f, you're using the last form, where the
pattern_list is a single argument, followed by zero or more files.

(The processing of directories with a -r option is a GNU extension.)

> I would prefer that my script does not impose any restriction on the search 
> patterns allowed
> by grep, because currently "$ptrn" is just a user-defined string.

In that case, use the -- indicator before the pattern.

grep -rl -- "$ptrn" "${dirlist[@]}"

This will ensure that grep doesn't treat the pattern as an option, even
if it happens to begin with a hyphen.



reply via email to

[Prev in Thread] Current Thread [Next in Thread]