shquoting

Invoking command with arguments from variable


I have a list of arguments, some which contain spaces, stored in a variable. When the command is invoked the arguments are not interpreted correctly. Here is a minimal example which illustrates the problem:

$ cat test.sh
echo $1
echo $2
$ sh test.sh foo "bar baz"
foo
bar baz
$ args='foo "bar baz"'
$ sh test.sh $args
foo
"bar

How should I pass args to make test.sh print this instead?

foo
bar baz

Solution

  • To interpret shell code that one constructs (incl grabbing from a variable), one uses eval.

    eval "sh test.sh $args"
    

    But is it really the best idea to put code in a variable?