Shell – bash adds extra single quotes

quotingshellssh

I have a problem executing my script.
When executing it in debug mode (bash -x), I can see that bash is adding extra quotes.
Therefor my script is failing.

Here this is within my script:

testvar="\"sudo /home/pi/shared/blink.sh 27 off\""
ssh -n -q -q -o BatchMode=yes -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=5 $1 ${testvar}

This is the output:

ssh -n -q -q -o BatchMode=yes -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o ConnectTimeout=5 192.168.42.105 '"sudo' /home/pi/shared/blink.sh 27 'off"'

Best Answer

Bash is displaying single quotes so as to show a command that is valid input syntax. It is not running a command which contains these single quotes in a parameter to the ssh command.

ssh … '"sudo' /home/pi/shared/blink.sh 27 'off"'

tells you that the last 4 parameters of the ssh command are "sudo, /home/pi/shared/blink.sh, 27 and off".

On the remote host, the ssh daemon joins the words of the commands with spaces as separators, so the remote command that you are executing is

"sudo /home/pi/shared/blink.sh 27 off"

This attempts to execute a command whose name is sudo /home/pi/shared/blink.sh 27 off, which of course doesn't exist.

Remove the double quotes from your definition of testvar.

It doesn't matter here, but it probably matters in your real case: instead of ${testvar}, write "$testvar" (or "${testvar}" if you want but the braces are optional). Always put double quotes around variable substitutions unless you know why you need to leave them out. "$testvar" expands to the value of the variable testvar, whereas $testvar when not in double quotes treats the value of testvar as a whitespace-separated list of glob patterns.

Related Question