Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

awk not working in bash -c "somecommand | awk '{print $2}'"

Tags:

bash

awk

subshell

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 "(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.

like image 736
Mark Nichols Avatar asked Nov 25 '25 09:11

Mark Nichols


1 Answers

Because you're in double quotes, $2 gets expanded by the shell, not passed literally to awk. And print in awk, by default, prints $0, ie. 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.

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:

# $'' 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.

bash -c 'dpkg -l | awk '"'"'/linux.+3[.]8[.]0.*44/ { print $2 }'"'"''
like image 53
Charles Duffy Avatar answered Nov 28 '25 03:11

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!