Sorunome
Sorunome

Reputation: 508

How to escape & in scp

Yes, I do realize it has been asked a thousand of times how to escape spaces in scp, but I fail to do that with the &-sign, so if that sign is part of the directory name.

[sorunome@sorunome-desktop tmp]$ scp test.txt "bpi:/home/sorunome/test & stuff"
zsh:1: command not found: stuff
lost connection

The & sign seems to be messing things quite a bit up, using \& won't solve the issue as then the remote directory is not found:

[sorunome@sorunome-desktop tmp]$ scp test.txt "bpi:/home/sorunome/test \& stuff"
scp: ambiguous target

Not even by omitting the quotes and adding \ all over the place this is working:

[sorunome@sorunome-desktop tmp]$ scp test.txt bpi:/home/sorunome/test\ \&\ stuff
zsh:1: command not found: stuff
lost connection

So, any idea?

Upvotes: 11

Views: 11925

Answers (5)

Alessandro Gastaldi
Alessandro Gastaldi

Reputation: 1

This is what worked for me:

function escape_file() {
    local ESCAPED=$(echo "$1" | sed -E 's:([ ()[!&<>"$*,;=?@\^`{}|]|]):\\\1:g' | sed -E "s/([':])/\\\\\1/g")
    echo "$ESCAPED"
}
REMOTE_FILE="/tmp/Filename with & symbol's! (xxx) [1.8, _aaa].gz"
scp "server:$(escape_ "$REMOTE_FILE")" /tmp/

Upvotes: 0

Maze
Maze

Reputation: 63

Surround the file name in an additional pair of \" like this:

scp "test.txt" "bpi:/home/sorunome/\"test & stuff\""

Since nothing needs to change inside the file name, this can be directly applied to variables:

scp "$local" "bpi:/home/sorunome/\"$remote\""

The outer quotes (") are interpreted by the local shell. The inner quotes (\") are interpreted on the remote server. Thanks to @chepner for pointing out how the arguments are processed twice.

Upvotes: 0

CDenby
CDenby

Reputation: 95

If you need to escape % use %%

Upvotes: 0

zeeshan07
zeeshan07

Reputation: 79

When using scp or cp, special characters can break the file path. You get around this by escaping the special character.

Using cp you can use the normal method of escaping special characters, which is preceding it with a backslash. For example, a path with a space could be copied using:

cp photo.jpg My\ Pictures/photo.jpg

The remote path in scp doesn’t work escaping using this method. You need to escape the special characters using a double backslash. Using the same example, the My Photos folder would have its space escaped using:

scp photo.jpg "user@remotehost:/home/user/My\\ Photos/photo.jpg"

The double quotes are also important, the whole path with the special characters must be enclosed with double quotes.

Source : https://dominichosler.wordpress.com/2011/08/27/using-scp-with-special-characters/

Upvotes: 0

Aaron
Aaron

Reputation: 24802

Escaping both the spaces and the ampersand did the trick for me :

scp source_file "user@host:/dir\ with\ spaces\ \&\ ampersand"

The quotes are still needed for some reason.

Upvotes: 14

Related Questions