0

I want to know whats the difference between look for a character with grep command with doble quotes, single quotes or none e.g.

grep ^'\' foo

grep ^"\" foo

grep \ foo

2
  • 1
    Did you run those? Note anything weird with the last two? (Also, grep is of no consequence here, you could try the same with echo instead.)
    – ilkkachu
    Feb 9 '20 at 21:21
  • It's not about grep, it's about shell. See mywiki.wooledge.org/Quotes
    – Ed Morton
    Feb 11 '20 at 22:33
1

You actually produced a bad example with the \ and putting the ^ outside the quotes.

The behavior of the quotes (or their absence) is determined by the shell that you use (I am assuming bash), and not by grep. As a general rule of thumb:

"  double quotes      Shell variables between the quotes are expanded
'  single quote       Shell variables do not get expanded
   no quotes          you can only use a single word, unless you escape the spaces.

So, keep in mind that the shell first does some interpretation, and then passes the arguments to grep.

Now some examples:

cat >afile <<EOF
a
aa
aaa
EOF
cat > abfile <<EOF
a
b
ab
aba
EOF
avar=a

We create two files afile and abfile and a shell variable avar.

grep 'a' afile will give:

a
aa
aaa

grep "a" afile will give:

a
aa
aaa

(the same). grep "$avar" afile will expand the variable avar to a and therefore, the result is

a
aa
aaa

However, grep '$avar' afile does not expand the variable avar, and therefore the result is:

(empty)

The abfile was created for the example without quotes. You should now understand why:

avar='a abfile'
grep $avar

gives:

a
ab
aba

Of course, if you want to find single quotes, you should grep "'" and vice-versa.

0

Any shell "word" consisting of quoted strings butted together is still a single argument. So you can make arguments out of parts with different rules.

Paul--) Q='One Two'
Paul--) J=A'${Q}'B"${Q}"C
Paul--) echo ::"${J}"::
::A${Q}BOne TwoC::
Paul--) echo ::${J}{Foo,Bar}::
::A${Q}BOne TwoCFoo:: ::A${Q}BOne TwoCBar::
Paul--) echo ::"${J}{Foo,Bar}"::
::A${Q}BOne TwoC{Foo,Bar}::

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.