[Eug-lug] Strange shell behavior
Martin Kelly
aomighty at gmail.com
Mon Jan 1 12:01:54 PST 2007
Yes, the example below would've worked... I think my problem was missing
double quotes screwing up the parsing of spaces. I actually don't have a
reason not to do it the simple way, however; it's just that I don't know
much about grep/bash. I think I'm going to use grep -lr, as it is giving
the output I wanted.
Thanks,
Martin
Bob Miller wrote:
> Martin Kelly wrote:
>
>> I have just written a shell script that greps a directory for a certain
>> pattern and reports each file that contains the pattern along with the
>> filename before it (this is why I wrote it... if I just do a "ls | cat |
>> grep pattern" or something like that it will report the text that
>> matches but not the filename).
>>
>> I am getting strange behavior in that it works, but sometimes it
>> randomly reports the contents of my / directory. This does not always
>> happen, only sometimes.
>
> Have you already considered and rejected doing it the simple way?
>
> $ cat misc/dirgrep
> #!/bin/sh
> cd "$1"
> shift
> grep "$@" *
> $ misc/dirgrep code/c/kr/1/ MAXLINE
> 1-16.c:#define MAXLINE 1000 /* maximum input line size */
> 1-16.c:char line[MAXLINE]; /* current input line */
> 1-16.c:char longest[MAXLINE]; /* longest line saved here */
> 1-16.c:while ((len = getline(line, MAXLINE)) > 0)
> 1-17.c:#define MAXLINE 1000 char line[MAXLINE]; while ((len = getline(line, MAXLINE)) > 0) {
>
> Also note that "grep -r ..." will recursively search subdirectories.
> That's useful sometimes. You could just say
>
> $ grep -r MAXLINE code/c/kr/1/
>
> If you have reason not to do it that way, you can fix your script by
> not using backslashes (it runs the output lines together) and by
> quoting $TEXT in the echo command.
>
> You don't need to save and restore the current directory. Each
> shell script runs in its own process, and each processs has its
> own current directory. So when the script exits, the kernel
> forgets its current directory.
>
> This would work.
>
> #!/bin/bash
> cd "$1" # note quotes
> for file in *
> do
> if grep -q "$2" "$file" # note quotes
> then
> echo
> echo "$file:"
> echo "-----------------------"
> grep "$2" "$file"
> fi
> done
>
More information about the EUGLUG
mailing list