Search code examples
bashawkwordscommand-substitution

Grouping command substitution without double quotes? "$()" without the ""


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.


Solution

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

    awk "$(echo 'BEGIN { print "hello!" }')"