1

I've found some anomaly when writing a script.

The following examples works as expected:

$ echo 123 | awk '{print $1 456}'
123456
$ sh -c "echo 123 | awk '{print $1}'"
123

But the following example, doesn't:

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

I'm expecting to print the 1st column with the additional string, which should return 123456 as it does when running the same command withoutsh -c. But what is happening, the 1st column is ignored for some reason. What's interesting, $1 is printed without problems when not performing string concatenation.

Why this is happening and how to do string concatenation within the command which is passed to separate instance of shell?

  • 2
    I think it may help you to understand what’s going on in this situation if you realize that your second example, sh -c "echo 123 | awk '{print $1}'", is “working for the wrong reason” – it’s not doing what you think it’s doing. Try sh -c "echo 123 456 | awk '{print $1}'" – it will print 123 456, because the $1 gets replaced by the current value of $1 in the shell (which is nothing) early in the interpretation of the command, so awk gets the command string {print }, causing it to print every line in its entirety, not just the first column. – G-Man Aug 29 '14 at 14:31
3

You must escape $ sign:

$ sh -c "echo 123 | awk '{print \$1 456}'"
123456

Otherwise, $1 is expanded by current shell.

  • Thank you, it works. Why I don't have to to escape it, when not doing string concatenation? – kenorb Aug 29 '14 at 10:42
  • 1
    @kenorb: because in this case, awk statement only have '{print}', which by default print $0. – cuonglm Aug 29 '14 at 10:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.