4

I am trying to sudo a command that uses Awk, and it looks like awk works differently inside sh -c.

echo '1 2' | awk '{print $2}'

2

sh -c "echo '1 2' | awk '{print $2}'"

1 2

Why is this happening?

Chris S
  • 77,945
  • 11
  • 124
  • 216
Michael Sofaer
  • 143
  • 1
  • 3

1 Answers1

4

You use double quotes, therefore $2 is evaluated. The inner single quotes don't affect this anymore. If $2 is empty, you are basically calling awk '{print }'. Consequently, you get the whole input line as output.

You could for example escape the $ with a backslash: \$2

Maxi
  • 176
  • 2
  • @Michael: You can see the behavior described by Maxi by using the `-x` option of the shell to show a trace: `sh -xc "echo '1 2' | awk '{print $2}'"` – Dennis Williamson Jun 29 '10 at 03:28