0

I'm writing a script that involves generating Awk programs and running them via awk $(...), as in

[lynko@hephaestus] ~ % awk $(echo 'BEGIN { print "hello!" }')

The generated program is going to be more complicated in the end, but first I want to make sure this is possible. In the past I've done

[lynko@hephaestus] ~ % program=$(echo 'BEGIN { print "hello" }')
[lynko@hephaestus] ~ % awk "$program"
hello!

where the grouping is unsurprising. But the first example (under GNU awk, which gives a more helpful error message than mawk which is default on my other machine) gives

[lynko@hephaestus] ~ % awk $(echo 'BEGIN { print "hello!" }')
awk: cmd. line:1: BEGIN blocks must have an action part

presumably because this is executed as awk BEGIN { print "hello!" } rather than awk 'BEGIN { print "hello!" }'. Is there a way I can force $(...) to remain as one group? I'd rather not use "$()" since I'd have to escape all the double-quotes in the program generator.

I'm running Bash 4.2.37 and mawk 1.3.3 on Crunchbang Waldorf.

Evelyn Kokemoor
  • 326
  • 1
  • 9

2 Answers2

1

Put quotes around it. You don't need to escape the double quotes inside it:

awk "$(echo 'BEGIN { print "hello!" }')"
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • In interactive shells, `!` is used for history substitution. You need to escape it as `\!`. This shouldn't affect scripting. – Barmar Jul 20 '14 at 09:33
1

I'm also wondering why you are using an echo statement. Awk doesn't need one.

awk 'BEGIN { print "Awk SQUAWK!" }'

That will work perfectly.

petrus4
  • 616
  • 4
  • 7
  • It was a contrived example to illustrate my problem (that I was misunderstanding `"$()"`). The actual code in question involves loops that transform command line arguments into appropriate awk statements. Which actually makes it very convenient that you can intermix BEGIN blocks with ordinary actions :) – Evelyn Kokemoor Jul 22 '14 at 08:35