0

In bash, this sequence doesn't work the way I thought it would:

> command="echo \"foo bar\""
> $command
"foo bar"

Using eval instead:

> eval $command
foo bar

This does what I want, but I would prefer not to use eval. Is there any way to formulate the expression "foo bar" such that the direct invocation $command sends the single intended argument to echo, instead of 2 half-quoted arguments?

For context, the script is a simple driver for compiler benchmarking, making it easy to experiment with various compiler options and organize the results for later analysis. There is no presentation factor to be accounted for, only the correct passing of arguments to the compiler, and correct naming of output file paths. Missed quotes lead to errors, whereas superficial factors like spaces are discarded by the compiler frontend and have no effect on the results.

4
  • Can you elaborate on why you need to do this? In general, it won't be reliable, e.g., with command="echo \"foo bar\"", you'll only have one space between foo and bar, not five, with either approach. Commented May 31 at 1:21
  • @JosephSible-ReinstateMonica: updated the question with context and objectives. Commented May 31 at 15:28
  • Remember that spaces aren't just for presentation. Consider a filename with multiple consecutive spaces in it. Commented May 31 at 16:05
  • Variables hold data. Functions hold code. Don't put code inside variables! See mywiki.wooledge.org/BashFAQ/050 for the issues and in particular mywiki.wooledge.org/BashFAQ/… how to do what you need to do to build a command on the fly.
    – Ed Morton
    Commented Jun 16 at 12:35

2 Answers 2

5

This does it, but still uses eval:

command='echo "foo bar"'
eval $command

Now, here it is without eval:

command=("echo" "foo bar")
"${command[@]}"
1
  • Thanks, I hadn't though about using an array to avoid ambiguous delimitation. It may take some significant changes in the scripts, but I'll give it a try and see if that resolves the issues. Commented May 31 at 15:31
1

While the array approach is the best way to do what you want (build a shell command equivalent to a parsed and cleaned input line), to answer the question asked you can use a function:

my_function(){ echo "foo bar"; }

command=my_function

$command # executes echo with one argument containing foo bar 

However in 48 years of Unix usage/programming I've never encountered a case where this was appropriate.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .