简体   繁体   English

为什么awk在使用eval时会打印整行?

[英]Why does awk print the full line when using eval?

I'm currently in the process of modifying a large BASH script which installs/checks a series of packages in a few different distros (mainly Redhat and Debian based). 我目前正在修改一个大型BASH脚本,该脚本在几个不同的发行版(主要是基于Redhat和Debian)中安装/检查一系列软件包。

To handle some of the differences between the distros (eg rpm vs dpkg, yum vs apt, etc) I'm trying to load some variables with various command strings so that the script isn't full of if debian then this, otherwise this statements. 为了处理发行版之间的一些差异(例如rpm vs dpkg,yum vs apt等),我试图用各种命令字符串加载一些变量,这样if debian then this, otherwise this脚本就if debian then this, otherwise this句话。 However it appears that awk doesn't like being put inside an eval statement, and I can't figure out why. 然而,似乎awk不喜欢被放入eval语句中,我无法弄清楚为什么。

Example

# Example dpkg --list output
# ii  bash       4.1-2ubuntu3    The GNU Bourne Again SHell

dpkg --list | grep 'bash'
# Outputs bash entries in dpkg.

cmd="dpkg --list | grep 'bash'"
eval $cmd                                       
# Outputs as expected, same as above.

dpkg --list | awk '/^.i/ { print $2 }'
# Outputs as expected, a list of package names.

cmd="dpkg --list | awk '/^.i/ { print $2 }'"
eval $cmd
# Awk prints full output from dpkg for every line matching the regex.

In the code above, simply grepping for a given package works fine, and prints as expected, but when trying to generate a full list of package names using awk, the print $2 appears to be ignored and simply prints the full line. 在上面的代码中,简单地为给定的包进行grepping工作正常,并按预期打印,但是当尝试使用awk生成包名的完整列表时, print $2似乎被忽略并且只打印整行。

Any ideas? 有任何想法吗?

This is the reason: 这就是原因:

cmd="dpkg --list | awk '/^.i/ { print $2 }'"
echo $cmd

Output:
dpkg --list | awk '/^.i/ { print }'

Escape the $ sign: 逃离$符号:

cmd="dpkg --list | awk '/^.i/ { print \$2 }'"

eval可以评估$ 2并用它的值替换它试试这个(转义$ char)。

cmd="dpkg --list | awk '/^.i/ { print \$2 }'"

You want this (gotta escape $ in awk script): 你想要这个(要在awk脚本中转义$):

cmd="dpkg --list | awk '/^.i.+bash/{ print \$2 }'"
eval $cmd

Still I do not understand why you use eval in this case, it causes several problems here, (one of which is that you apparently cannot use /^.i.*bash/ regex (shell expands glob or passes \\ inside regex) and have to resolve to /^.i.+bash/ . 我仍然不明白为什么你在这种情况下使用eval ,它会导致几个问题,(其中一个是你显然不能使用/^.i.*bash/正则表达式(shell扩展glob或传递\\正则表达式内部)并且有解析为/^.i.+bash/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM