Search code examples
bashsu

Missing matching quote with su -c in bash script


I want to write something like

EXEC="sudo su -m root -c \"java Something\""
$EXEC &

But i get the following error:

Something": -c: line 0: unexpected EOF while looking for matching `"'
Something": -c: line 1: syntax error: unexpected end of file

If I write the command on the command line it executes. If I have it stored in a variable and trying to extrapolate it - it does not. Why?


Solution

  • Try this:

    exec="ls -l \"/a b c\""
    $exec
    

    You will see something like:

    ls: cannot access "/a: No such file or directory
    ls: cannot access b: No such file or directory
    ls: cannot access c": No such file or directory
    

    Which shows exactly where the problem is - that is - expansion of variable is done after word splitting.

    To make it work, you can use eval:

    =$ eval "$exec"
    ls: cannot access /a b c: No such file or directory
    

    or even:

    =$ sh -c "$exec"
    

    Or better yet, don't make such commands to run. Not sure what is the purpose of it, but think about avoiding building full command lines in variables.