Search code examples
bashescapingquotes

Bash, exec and the quoting hell


How can I preserve single and double quotes when running a command using exec?

#!/bin/sh

CMD="erl -eval 'erlang:display("foo")'"
exec $CMD

Tried with backslashes, but didn't help. For example, if I do what it would sound ovious to me:

#!/bin/sh

CMD="erl -eval 'erlang:display(\"foo\")'"
echo $CMD
exec $CMD

I get as output of the echo exactly what I want, but the command is not executed correctly when using exec.

I'm working on Snow Leopard.

Any help?


Solution

  • Try using an array:

    CMD=(erl -eval 'erlang:display("foo")')
    echo "${CMD[@]}"
    "${CMD[@]}"