我有一个脚本 myScript,它试图将脚本参数写入文件中。不知何故,变量扩展无法与egrep命令正常工作。我相信我已经将示例中的问题隔离如下:如果我在脚本中显式写出参数,则egrep命令可以工作,但是如果我将参数传递给脚本,则egrep命令不喜欢参数I发送。
#!/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
当我运行这个脚本时,
myScript dog
输出为:
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
非常感激任何的帮助。
答案1
更改以下行:
grepFails=$(egrep "\\def$myVar\>" myFile)
和:
grepFails=$(egrep "\\\\def\\$myVar\>" myFile)
问题是您没有\
在子 shell 中正确转义。
要理解,请尝试运行eval echo "\\\\"
.您会注意到输出是\
由于双重评估而产生的。