2

I noticed that this works fine (will print only the PID of unattended-upgrades process):

lslocks | awk '/unattended-upgrades/ { print $2 }'

But this effectively ignores the print part (will print the entire line):

bash -c "lslocks | awk '/unattended-upgrades/ { print $2 }'"

This is an Ubuntu 18.04 and Bash version 4.4.20.

What is spacial about bash -c that causes this?

yujaiyu
  • 239

1 Answers1

6

There's nothing special about bash -c here - it's the fact that the outer double quotes permit expansion of $2 by the interactive shell:

$ set -x
$ bash -c "echo foo bar | awk '{ print $2 }'"
+ bash -c 'echo foo bar | awk '\''{ print  }'\'''
foo bar

(The "gotcha" here is that single quotes are not special inside double quotes; the outer double quotes "preserve their literal value". See Bash Reference Manual 3.1.2.3 Double Quotes.)

Compare:

$ bash -c "echo foo bar | awk '{ print \$2 }'"
+ bash -c 'echo foo bar | awk '\''{ print $2 }'\'''
bar
steeldriver
  • 81,074