Fix ssh command quoting
SSH only takes a simple string as command to send to the remote end 1. In other words, ssh has to concatenate all arguments with a space as separator.
Example:
In this case, my local ssh program gets the command
['echo', 'Hello', 'World'] from the system, build the command string
'echo Hello World' from, sends it to my server, and the ssh process
there will give this command string to the shell, which will expand it
into the 3 separate parts again.
You can see the command string if you give ssh the -v option and have
a look for the line with debug1: Sending command:.
If I run the “same” command on my local system, I get the same output:
Now lets try something else:
What did happen now?
With ssh, my local ssh program got ['echo Hello World'] - but the
command it sent was the same, so the server printed the same line as
before.
But my local shell still sees the quotes around, and won’t split it - that is what quotes are for.
This behaviour allows tricks like this one:
On my local system '*' won’t get expanded as it is quoted, but the
remote end doesn’t have the quotes anymore, and the shell will expand
it.
So what is the problem?
printf is a nice tool to output stuff in a formatted way. Now lets try
that with ssh:
I added the echo X so you can see that my server didn’t even print a
newline.
This is not what I wanted to see though - how did this happen?
$ ssh -v stbuehler.de printf '%-10s %s\n' Hello World
[...]
debug1: Sending command: printf %-10s %s\\n Hello World
[...]
$ printf %-10s %s\\n Hello World; echo X
%s\n Hello World X
As it looses the quotes around my arguments (which contained spaces), it breaks the first argument up, which leads to a completely different result.
I think this is a bug - you would expect that a command with ssh works the same way as it does local. For this the command should have been designed as a list of strings in the SSH Protocol. Nobody will fix this now ofcourse, so we will have to work around that.
Someone else had the same problem over at https://stackoverflow.com/questions/6592376/prevent-ssh-from-breaking-up-shell-script-parameters, and the answers show how to workaround it. But I wanted a new “ssh” program, that would fix this for me. I named it sshsystem, and it works:
Yes!
Other fun you can have:
$ ssh stbuehler.de echo Foo ';' echo Bar
Foo
Bar
$ ssh stbuehler.de echo Foo $'\n' echo Bar
Foo
Bar
$ sshsystem stbuehler.de echo Foo $'\n' echo Bar
Foo
echo Bar
(The shell on the other side can execute more than one command - either
split them with ; or \n - quoted ofc, otherwise your local shell
will interpret them)
Source is available at https://gist.github.com/4672115, https://stackoverflow.com/questions/6592376/prevent-ssh-from-breaking-up-shell-script-parameters/14601289#14601289 and below.