简体   繁体   English

awk无法在bash -c中运行“ somecommand | awk'{print $ 2}''”

[英]awk not working in bash -c “somecommand | awk '{print $2}'”

This command works as expected: 此命令按预期工作:

(dpkg -l | egrep "linux.+3.8.0.*44" | awk '{print $2}')
linux-generic-lts-raring
linux-headers-3.8.0-44
linux-headers-3.8.0-44-generic
linux-headers-generic-lts-raring
linux-image-3.8.0-44-generic
linux-image-generic-lts-raring

However, when I run it with bash -c it doesn't work: 但是,当我使用bash -c运行它不起作用时:

bash -c "(dpkg -l | egrep "linux.+3.8.0.*44" | awk '{print $2}')"
ii  linux-generic-lts-raring         3.8.0.44.44                       Generic     Linux kernel image and headers
ii  linux-headers-3.8.0-44           3.8.0-44.66~precise1              Header files related to Linux kernel version 3.8.0
ii  linux-headers-3.8.0-44-generic   3.8.0-44.66~precise1              Linux kernel headers for version 3.8.0 on 64 bit x86 SMP
ii  linux-headers-generic-lts-raring 3.8.0.44.44                       Generic Linux kernel headers
ii  linux-image-3.8.0-44-generic     3.8.0-44.66~precise1              Linux kernel image for version 3.8.0 on 64 bit x86 SMP
ii  linux-image-generic-lts-raring   3.8.0.44.44                       Generic Linux kernel image

I have no clue why. 我不知道为什么。 It's almost as if the pipe is breaking. 好像管道破裂了。

Because you're in double quotes, $2 gets expanded by the shell, not passed literally to awk . 因为您用双引号引起来,所以$2会被shell扩展,而不是直接传递给awk And print in awk, by default, prints $0 , ie. 并且在awk中print ,默认情况下打印$0 ,即。 the entire line of input, so if it's expanded to an empty value, there's your problem. 整个输入行,因此,如果将其扩展为空值,则会出现问题。

bash -c "(dpkg -l | egrep 'linux.+3.8.0.*44' | awk '{print \$2}')"

By the way -- there's no point to using grep and awk separately. 顺便说一句-没有必要单独使用grepawk

bash -c "dpkg -l | awk '/linux.+3.8.0.*44/ { print \$2 }'"

If your enclosing shell is itself bash, then one can use $'' as an alternate means to provide literal strings: 如果封闭的外壳本身是bash,则可以使用$''作为提供文字字符串的替代方法:

# $'' only works with bash, ksh, etc., but won't interpret $2, and lets
# you pass literal quotes
bash -c $'dpkg -l | awk \'/linux.+3[.]8[.]0.*44/ { print $2 }\''

By contrast, if your enclosing shell is baseline POSIX, including literal single-quotes inside a single-quoted string gets a bit more complicated. 相比之下,如果封闭的外壳是基线POSIX,则在单引号字符串中包含文字单引号会变得更加复杂。

bash -c 'dpkg -l | awk '"'"'/linux.+3[.]8[.]0.*44/ { print $2 }'"'"''

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

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