Grep problem from The Unix Programming Environment

Hi

Here is the problem ( Exercise 3-3, Using The Shell of The Unix Programming Environment, Kerninghan, Pike, 3rd edition ):

Predict what each of the following grep commands will do, and then verify your understanding.

grep \$
grep \\$
grep \\\$
grep '\$'
grep '\'$'
grep \\
grep \\\\
grep "\$"
grep '"$'
grep "$"

[i]A file containing these commands themselves makes a good test case if you want to experiment.

Needless to say, my understanding was wrong.

The first command for example, prints all lines, which I don't understand - so I suppose I must be missing on basics.

Any hints will be highly appreciated.

Please post sample data (very important that the data includes lines containing one or more dollar character and some lines with various numbers of backslash characters) , the commands you typed, the results and any comments about what happened. I really like the idea of using the example grep lines as sample data because they seem to contain every variant.
While doing this task you will probably understand the basic concepts.

Please mention what Operating System and version you are running and what Shell you use. I can't imagine that it will be the original Bourne Shell (but it might be).

In unix fundamental commands, the dollar sign can mean the end of the line. When not escaped it introduces an Environment Variable. When double-quoted and escaped "\$" it becomes just a dollar character. When single-quoted it is just a dollar character '$' because single quotes disable parameter substitution. This example appears to be about teaching the fundamentals. If you use grep to look for end-of-line characters in a normal unix text file the output will be every line.

In the first example the grep is looking for end-of-line characters in a text file (i.e. line-feed characters) which are abbreviated to a dollar sign in much unix syntax. The dollar sign has been escaped with a backslash to stop it being interpreted by Shell as an introduction to an Environment Variable.

1 Like

I suggest that you examine the problem one step at a time.

The first question is, what will the shell do to the arguments?

To see that, replace grep with echo :

echo \$
echo \\$
echo \\\$
echo '\$'
echo '\'$'
echo \\
echo \\\\
echo "\$"
echo '"$'
echo "$"

Whatever is printed is what will be passed to grep .

Try them separately as one line contains an error that will affect subsequent lines if you run them all as a single script.

1 Like

Thank you very much guys for your replies. I understand it better now!