【基本介绍】
在编写shell脚本的时候也会经常出现“/bin/grep: |: No such file or directory”类似的错误,特别是在执行的命令是变量的情况
【简单案例】
[code="shell"]
# cat aa.sh
aa="/bin/grep Accepted /root/test.log | /bin/grep -v something"
tmp=`$aa`
# bash aa.sh
/bin/grep: |: No such file or directory
/bin/grep: something: No such file or directory
[/code]
解决方法可以使用eval命令
[code="shell"]
# cat aa.sh
aa="/bin/grep Accepted /root/test.log | /bin/grep -v something"
tmp=`eval $aa`
# bash aa.sh
#
#
[/code]
【eval】
eval命令将会首先扫描命令行进行所有的替换,然后再执行命令。该命令使用于那些一次扫描无法实现其功能的变量。该命令对变量进行两次扫描。这些需要进行两次扫描的变量有时候被称为复杂变量。
[code="shell"]
# cat dd.sh
X=10
Y=X
echo '$'$Y
echo $$Y
echo ${$Y}
eval echo '$'$Y
# bash dd.sh
$X
40342Y
dd.sh: line 5: ${$Y}: bad substitution
10
[/code]
【参考】
[url]http://www.softpanorama.org/Utilities/eval.shtml[/url]
[url]http://kmoving.blog.163.com/blog/static/205049197201242511250128/[/url]
在编写shell脚本的时候也会经常出现“/bin/grep: |: No such file or directory”类似的错误,特别是在执行的命令是变量的情况
【简单案例】
[code="shell"]
# cat aa.sh
aa="/bin/grep Accepted /root/test.log | /bin/grep -v something"
tmp=`$aa`
# bash aa.sh
/bin/grep: |: No such file or directory
/bin/grep: something: No such file or directory
[/code]
解决方法可以使用eval命令
[code="shell"]
# cat aa.sh
aa="/bin/grep Accepted /root/test.log | /bin/grep -v something"
tmp=`eval $aa`
# bash aa.sh
#
#
[/code]
【eval】
eval命令将会首先扫描命令行进行所有的替换,然后再执行命令。该命令使用于那些一次扫描无法实现其功能的变量。该命令对变量进行两次扫描。这些需要进行两次扫描的变量有时候被称为复杂变量。
[code="shell"]
# cat dd.sh
X=10
Y=X
echo '$'$Y
echo $$Y
echo ${$Y}
eval echo '$'$Y
# bash dd.sh
$X
40342Y
dd.sh: line 5: ${$Y}: bad substitution
10
[/code]
【参考】
[url]http://www.softpanorama.org/Utilities/eval.shtml[/url]
[url]http://kmoving.blog.163.com/blog/static/205049197201242511250128/[/url]