When I write
$ grep \$
then whatever I type on terminal, is matched and printed on terminal. How is \$ being interpreted?
When I write
$ grep \$
then whatever I type on terminal, is matched and printed on terminal. How is \$ being interpreted?
The shell is interpreting the \$ and passing it through to grep as $, the end of line character. So assuming your line has an end, it will match :-)
If you want to match an actual $ in grep, use one of:
grep \\\$
grep '\$'
In the former, the shell interprets \\ as \ and \$ as $, giving \$. In the latter, it doesn't interpret it at all.
As to your question as to why \$ matches the dollar sign rather the the two-character sequence, regular expressions like those used in grep use special characters for some purposes. Some of those are:
$ end of line
^ start of line
. any character
+ 1 or more of the preceeding pattern
* 0 or more of the preceeding pattern
{n,m} between n and m of the preceeding pattern
[x-y] any character between x and y (such as [0-9] for a digit).
along with many others.
When you want to match a literla character that's normally treated as a special character, you need to escape it so that grep will treat it as the normal character.
The shell first expands any escape sequences before passing the arguments to the program, so it interprets the \$ as an escape sequence and passes the single argument $ to grep, which matches the end of line. Since every line has an end, then any line should match :)
It's being interpreted as the end-of-line metacharacter. If you want to match an actual dollar sign, do
$ grep \\$
or
$ grep '\$'
^ is for start of string, and $ for end.
grep \$
or
grep $
will match every string, so anything you type is echoed back.
Try
grep a$
Now, only strings whose last character is a will be matched and echoed.
You can save the trouble of escaping if you want to search for a literal $, by using the regular expression for the character class. For example,
$ grep '[$]' file