2

This correctly prints test

$ echo 'this is a test' | awk '{print $4}'
test

While using this command inside /bin/bash -c does not work

/bin/bash -c "echo 'this is a test' | awk '{print $4}'"
this is a test

How can I get awk to work correctly when using with /bin/bash -c?

Catfish
  • 17,987
  • 50
  • 195
  • 342

1 Answers1

5

$4 is expended by shell since you have double quoted command string.

You can check trace output by adding -x in bash command line:

bash -xc "echo 'this is a test' | awk '{print $4}'"
+ echo 'this is a test'
+ awk '{print }'
this is a test

Since $4 expands to an empty string it effectively runs awk '{print }' and thus complete line is printed in output.

To fix this, you should be using an escaped $ to avoid this expansion:

bash -c "echo 'this is a test' | awk '{print \$4}'"
test
anubhava
  • 713,503
  • 59
  • 514
  • 593