How to escape spaces in path during scp copy in Li

2019-01-16 00:35发布

问题:

I'm new to linux, I want to copy a file from remote to local system... now I'm using scp command in linux system.. I have some folders or files names are with spaces, when I try to copy that file, it shows the error message: "No such file or directory"

I tried:

scp ael5105@192.168.0.200:'/home/5105/test/gg/Untitled Folder/a/qy.jpg' /var/www/try/

I saw the some reference online but I don't understand perfectly, can any one help on this?

how can I escape spaces in file name or directory names during copying...

回答1:

Basically you need to escape it twice, because it's escaped locally and then on the remote end.

There are a couple of options you can do (in bash):

scp user@example.com:"'web/tmp/Master File 18 10 13.xls'" .
scp user@example.com:"web/tmp/Master\ File\ 18\ 10\ 13.xls" .
scp user@example.com:web/tmp/Master\\\ File\\\ 18\\\ 10\\\ 13.xls .


回答2:

works

scp localhost:"f/a\ b\ c" .

scp localhost:'f/a\ b\ c' .

does not work

scp localhost:'f/a b c' .

The reason is that the string is interpreted by the shell before the path is passed to the scp command. So when it gets to the remote the remote is looking for a string with unescaped quotes and it fails

To see this in action, start a shell with the -vx options ie bash -vx and it will display the interpolated version of the command as it runs it.



回答3:

Also you can do something like:

scp foo@bar:"\"apath/with spaces in it/\""

The first level of quotes will be interpreted by scp and then the second level of quotes will preserve the spaces.



回答4:

I had huge difficulty getting this to work for a shell variable containing a filename with whitespace. Turns out that using

file="foo bar/baz"
scp user@example.com:"'$file'"

as in @Adrian's answer seems to fail (try entering set -x before the above commands to see how the shell interprets this string; it is pretty wonky and I do not really understand why it fails).

Turns out that what works best is using a parameter expansion to to prepend backslashes to the whitespace, as follows.

file="foo bar/baz" # a file inside a directory-name with whitespace
file="${file//\ /\\\ }" # the `//` replaces all instances; `/` just replaces the first
scp user@example.com:"$file"


回答5:

Use 3 backslashes to escape spaces in names of directories:

scp user@host:/path/to/directory\\\ with\\\ spaces/file ~/Downloads

should copy to your Downloads directory the file from the remote directory called directory with spaces.