Passing a variable argument to egrep in a bash script
7,136
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.
Related videos on Youtube
Author by
Leo Simon
Updated on September 18, 2022Comments
-
Leo Simon over 1 year
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.
-
RobertL over 8 yearsAnother 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).