On 2020-05-14, loic.tregouet wrote:
> Hi,
> 
> I've reproduced a strange behaviour of grep command when a file
> name of a single letter is present in current directory .
> 
> $ echo a | grep [a-z]
> a
> $ touch t
> $ echo a | grep [a-z]
> $ rm t
> $ echo a | grep [a-z]
> a
> $
> 
> 
> Any idea ?

You are not quoting the pattern so it is being expanded by the
shell.  The shell sees the argument as a pathname pattern to be
expanded.  If there is no matching file name, the shell leaves the
argument unchanged and passes [a-z] to grep.  If there is a matching
file name, as there is after you touch t, then the shell expands
that pattern to the matching file t and passes t to grep.

The solution is to enclose the pattern in quotes, either single or
double, like this:

    $ echo a | grep "[a-z]"

or to escape one or both of the brackets, like this:

    $ echo a | grep \[a-z\]

Regards,
Gary




Reply via email to