On 2/27/22 11:31, Marja Koivunen wrote:
Maybe what is possible is to add a line to manual that explains that certain 
filenames that are OK in modern OS might not work with grep.

I have used “-" sometimes to keep certain file at the top of directory 
hierarchy. In this case I was organizing libraries and marked those that I was not 
using with “-“.

Although that practice is tempting, it is probably not a good idea on any platform where you might use shell commands. POSIX says portable file names can't begin with '-'.

There is a section of the grep manual that talks about this but perhaps it is not clear enough. I installed the attached patch to try to make it better.
From efe1e1543c409504752f8d240d3ea41af3b8fddf Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Sun, 27 Feb 2022 15:15:51 -0800
Subject: [PATCH] =?UTF-8?q?doc:=20more=20on=20leading=20=E2=80=98-?=
 =?UTF-8?q?=E2=80=99?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit

* doc/grep.texi (Usage): Expand on leading ‘-’ problems (Bug#54174).
---
 doc/grep.texi | 32 +++++++++++++++++++++++---------
 1 file changed, 23 insertions(+), 9 deletions(-)

diff --git a/doc/grep.texi b/doc/grep.texi
index ebbefda..f0ea1c3 100644
--- a/doc/grep.texi
+++ b/doc/grep.texi
@@ -1719,25 +1719,39 @@ grep -r --include='*.c' 'hello' /home/gigi
 
 @item
 What if a pattern or file has a leading @samp{-}?
+For example:
+
+@example
+grep "$pattern" *
+@end example
+
+@noindent
+can behave unexpectedly if the value of @samp{pattern} begins with @samp{-},
+or if the @samp{*} expands to a file name with leading @samp{-}.
+To avoid the problem, you can use @option{-e} for patterns and leading
+@samp{./} for files:
 
 @example
-grep -- '--cut here--' *
+grep -e "$pattern" ./*
 @end example
 
 @noindent
-searches for all lines matching @samp{--cut here--}.
-Without @option{--},
-@command{grep} would attempt to parse @samp{--cut here--} as a list of
-options, and there would be similar problems with any file names
-beginning with @samp{-}.
+searches for all lines matching the pattern in all the working
+directory's files whose names do not begin with @samp{.}.
+Without the @option{-e}, @command{grep} might treat the pattern as an
+option if it begins with @samp{-}.  Without the @samp{./}, there might
+be similar problems with file names beginning with @samp{-}.
 
-Alternatively, you can prevent misinterpretation of leading @samp{-}
-by using @option{-e} for patterns and leading @samp{./} for files:
+Alternatively, you can use @samp{--} before the pattern and file names:
 
 @example
-grep -e '--cut here--' ./*
+grep -- "$pattern" *
 @end example
 
+@noindent
+This also fixes the problem, except that if there is a file named @samp{-},
+@command{grep} misinterprets the @samp{-} as standard input.
+
 @item
 Suppose I want to search for a whole word, not a part of a word?
 
-- 
2.32.0

Reply via email to