Bash – How to run the following command with curly braces in bash

bashcommand line

I a bash script I have the following

CMD="{ head -n1 $DATE.$FROMSTRAT.new && egrep -i \"$SYMS\" $DATE.$FROMSTRAT.new; } > $DATE.$TOSTRAT.new" 
echo "Running $CMD"                                                                                     
`$CMD`                                                                                                  

When I call the script

Running { head -n1 inputFile.new && egrep -i "X|Y" inputFile.new; } > outputFile.new
script.sh: line 17: {: command not found 

But when I run { head -n1 inputFile.new && egrep -i "X|Y" inputFile.new; } > outputFile.new on the command line it works fine.

I try to escape the { with no success, how can I do this ?

Best Answer

Well, if you use a variable on the command line like that, it will be split to words, but that happens after syntactical items like { (or if) are parsed. So, if you want that, you'll have to use eval

CMD="{ echo blah ; echo bleh; } > output"
eval "$CMD"
# output contains "blah" and "bleh"

Though note eval will run everything in the variable in the current shell, including assignments to variables (changing IFS may have funny effects for the rest of the script, say). You could run it in a separate shell with bash -c "$CMD" to mitigate at least the variable assignment issue.

Also note that the backticks are used to capture the output of a command, and use it on the command line, so this would run the output of $CMD also as a command:

$ CMD="echo foo"
$ `$CMD`
-bash: foo: command not found

If you're redirecting the output to a file, it won't matter, but you most likely also don't need it.

Related Question