1

I have a script, myScript, which is trying to egrep the script argument in a file. Somehow variable expansion isn't working properly with the egrep command. I believe I've isolated the problem in the example as follows: if I write out the argument explicitly in the script, the egrep command works, but if I pass the argument to the script, the egrep command doesn't like the argument I send it.

#!/bin/bash
echo "\def\\$1" > myFile
echo "\def\\$1$1" >> myFile

myVar=\\$1
echo myVar is "$myVar"

grepWorks=$(egrep '\\def\\dog\>' myFile)
echo Without a variable, grep output is $grepWorks

echo Pattern string fed to grep with variable myVar is  "\\def$myVar"
grepFails=$(egrep "\\def$myVar\>" myFile)
echo With a variable, grep output is $grepFails

When I run this script with,

myScript dog

the output is:

myVar is \dog
Without a variable, grep output is \def\dog
Pattern string fed to grep with variable myVar is \def\dog
With a variable, grep output is

Any help would be most appreciated.

3

Change the following line:

grepFails=$(egrep "\\def$myVar\>" myFile)

With:

grepFails=$(egrep "\\\\def\\$myVar\>" myFile)

The problem was that you were not escaping the \ properly in the subshell.

To understand, try running eval echo "\\\\". You will notice that the output is \ because of the double evaluation.

2
  • Another possiblity is: '\\'def"$myVar"'\>' (kind of a tradeoff between backslashes and quotes, take your pick). Also, I'm not sure if you need the \` before the $myVar` (at least I didn't see it in the question).
    – RobertL
    Nov 20 '15 at 18:23
  • Thanks @Kira, and RobertL Certainly fixes my problem. Curious about the double evaluation: when egrep is passed an argument in double quotes, is that when the first evaluation happens, and then egrep itself does the second evaluation? whereas, when egrep is passed an argument in single quotes, there's only one evaluation? Is so, then I think I understand what's going on!!
    – Leo Simon
    Nov 20 '15 at 23:34

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.