5

Why does the awk command not produce the same results with simple-quotes and double-quotes?

root@vm90:/root# who | awk "{ print $2 }"
...
root@vm90:/root# who | awk '{ print $2 }'
...

I'd like to use awk in a PHP shell_exec() function, which uses simple-quotes in the entire code.

This ...

$output = shell_exec("who | awk '{ print $2 }'");

... works, but I prefer ...

$output = shell_exec('who | awk "{ print $2 }"');

... this, which doesn't work.

geohei
  • 696
  • 4
  • 15
  • 4
    `$2` within double quotes gets expanded by bash. So in fact, to use awk's `$2` you need to escape it: `who | awk "{ print \$2 }"`. – fedorqui May 28 '14 at 10:31

1 Answers1

4

From the GNU Awk manual (emphasis added):

Because certain characters within double-quoted text are processed by the shell, they must be escaped within the text. Of note are the characters $, `, \, and ", all of which must be preceded by a backslash within double-quoted text if they are to be passed on literally to the program. (The leading backslash is stripped first.)

mklement0
  • 382,024
  • 64
  • 607
  • 775
mrks
  • 8,033
  • 1
  • 33
  • 62