[chuug] Confusing script behavior
Jeff King
peff-chuug at peff.net
Sat Nov 4 00:47:15 EST 2006
On Fri, Nov 03, 2006 at 08:22:52PM -0500, David Clymer wrote:
> I've been fiddling with scripts that act on themselves. So I've created
> a script that is supposed to be grepping its contents, however it is
> behaving in ways I don't expect. For example (the script's name is
> "foo"):
>
> david at zepto:~$ cat foo
> #! /bin/grep '^#'
>
> # ./foo blah
>
> this is a test
> david at zepto:~$ ./foo
> #! /bin/grep '^#'
>
> Why is it only matching the first line? Perhaps grep isn't interpreting
The single quotes around ^# don't make any sense on Linux (which it
looks like you're running based on your firewall script). The kernel
does something like this for your case:
argv[0] = "/bin/grep";
argv[1] = "'^#'";
argv[2] = "./foo";
execv(argv[0], argv);
See fs/binfmt_script.c in the kernel source for the (fairly simple)
parsing magic. You get an interpreter and one optional argument,
separated by a space, with no quoting.
So you're _really_ grepping for '^#', including the quotes. Of course
that won't match your second line. On my system, it doesn't even match
the first line! However, I can imagine a grep in which a
beginning-of-line anchor not at the beginning of a pattern is treated as
a literal caret (^), since otherwise it would be unmatchable. In this
case it is matching _not_ the hash mark at the beginning of the first line,
but the actual grep pattern from the end of the line.
My grep is GNU grep 2.5.1; I imagine you have a different version that
behaves as I specified above. Hmm. In fact, it looks like this has been
reported as a bug and fixed in the last 2 months:
http://savannah.gnu.org/bugs/?17492
-Peff
More information about the Chuug
mailing list