sh -c: Unterminated quoted string error

26,060

Solution 1

That cannot work. When your shell performs word splitting, you will have four arguments:

sh
-c
'echo
"a"'

To accomplish this, you must use a bash array:

cmd=( sh -c 'echo "a"' )
"${cmd[@]}"

Solution 2

The main error here is thinking that the single quotes around 'echo \"a\"' would stop "word splitting" performed by the shell and pass echo "a" as a single argument to sh.

In this case, the single quotes are actually treated as "literal" not "syntactical" because they are included within the outer double quotes!

The following link helped me the most: http://mywiki.wooledge.org/Arguments

Share:
26,060

Related videos on Youtube

yeachan park
Author by

yeachan park

Updated on September 18, 2022

Comments

  • yeachan park
    yeachan park over 1 year

    I've spent hours trying to understand the following error.

    My Script

    CMD="sh -c 'echo \"a\"'"
    $CMD
    

    Error:

    "a"': 1: "a"': Syntax error: Unterminated quoted string
    

    of course when I do echo $CMD and paste the result, it works as expected...

    What is the cause of the error?

    Edit:

    I'm asking for an explanation not only a workaround. Therefore, I think the following link doesn't answer my question: Quoting in a function results in error

  • yeachan park
    yeachan park about 9 years
    Thanks, I didn't know aboud word splitting performed by the shell, I'm going to check this out!
  • Angel Todorov
    Angel Todorov about 9 years
  • Angel Todorov
    Angel Todorov about 9 years
    Also, spend some time with the bash manual: gnu.org/software/bash/manual/bashref.html#Shell-Expansions
  • yeachan park
    yeachan park about 9 years
    see my answer below! thanks for pointing me in the right direction!