11

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"'
7

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.

3

I think that you should use:

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 working for me:

$ bash -x -c 'testvar="la la la"; echo "${testvar}"'
+ testvar='la la la'
+ echo 'la la la'
la la la

But if I write the same like you did, I get the same wrong result:

$ bash -x -c 'testvar="\"la la la\""; echo ${testvar}'
+ testvar='"la la la"'
+ echo '"la' la 'la"'
"la la la"
  • The quotes are crucial because they are the shell's mechanism to group several words together to form a single argument. – glenn jackman Jan 21 '14 at 1:10
2

Shell splits the value of the variable into words. Doublequote it to prevent the splitting. See the difference:

t='"a b c"'
set -xv
echo $t
echo "$t"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.