Escape username spaces in SCP

I've been playing around with SCP for a while, and I've been able to transfer files from one place to another. It all worked nicely until I needed to copy a file from Ubuntu to a Windows user who had spaces in his username (* groan *)

While I got it working for SSH like this:

ssh "User Name Spaces"@192.168.0.42

It didn't work with SCP:

scp "myfile.txt" "User Name Spaces"@192.168.0.42:folder

As it returns:

User Name Spaces: invalid user name

I've tried all kinds of things:

scp "myfile.txt" "User Name Spaces"@192.168.0.42:folder
scp "myfile.txt" "User\ Name\ Spaces"@192.168.0.42:folder
scp "myfile.txt" "User\\ Name\\ Spaces"@192.168.0.42:folder
scp "myfile.txt" "User\\\ Name\\\ Spaces"@192.168.0.42:folder
scp "myfile.txt" "'User Name Spaces'"@192.168.0.42:folder
scp "myfile.txt" "'User\ Name\ Spaces'"@192.168.0.42:folder
scp "myfile.txt" "'User\\ Name\\ Spaces'"@192.168.0.42:folder
scp "myfile.txt" "'User\\\ Name\\\ Spaces'"@192.168.0.42:folder
scp "myfile.txt" "'User Name Spaces'@192.168.0.42":folder

And so on... but nothing seems to work

Does anyone have any ideas?


You could use ~/.ssh/config. It's the per-user configuration file for SSH (and commands based on SSH like scp and sftp). Create it, if it does not exist, and add:

Host 192.168.0.42
    User "User Name Spaces"

For example:

Host localhost
    User "foo bar"

Then:

$ scp test.txt  localhost:
foo bar@localhost's password: 

(I don't actually have a user named foo bar, so I couldn't finish the test.)


You could also create an alias in .ssh/config:

Host foo
    Hostname 192.168.0.42
    User "User Name Spaces"

Then you can conveniently do:

ssh foo
scp file foo:

And avoid having to type the whole IP address.


An alternative, if you have tar available on both ends:

tar c myfile.txt | ssh "User Name Spaces"@192.168.0.42 tar x

tar creates a tar archive, saved to standard output and piped through to SSH, where it becomes the input to tar x, which extracts the archive. You can use options like -C to change the directory (or do so as a shell command before tar: ssh … 'cd foo; tar x). You could also use compression and save a bit on network bandwitdh:

tar zc myfile.txt | ssh "User Name Spaces"@192.168.0.42 tar zx