如何逃脱 & in scp

How to escape & in scp

是的,我知道有人问过上千次如何在 scp 中转义 spaces,但我没能用 &-符号,如果该符号是目录名称的一部分。

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

& 符号似乎把事情搞得一团糟,使用 \& 无法解决问题,因为找不到远程目录:

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

即使省略引号并在所有地方添加 \ 也行不通:

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

那么,有什么想法吗?

转义空格和符号对我有用:

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

出于某种原因仍然需要引用。

使用 scp 或 cp 时,特殊字符可能会破坏文件路径。您可以通过转义特殊字符来解决这个问题。

使用 cp,您可以使用转义特殊字符的常规方法,即在其前面加上反斜杠。例如,可以使用以下方式复制带有 space 的路径:

cp photo.jpg My\ Pictures/photo.jpg

scp中的远程路径用这种方法转义是不行的。您需要使用双反斜杠转义特殊字符。使用相同的示例,我的照片文件夹将使用 space 转义:

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

双引号也很重要,有特殊字符的整个路径都要用双引号括起来。

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

如果需要转义 % 使用 %%

用一对 \" 将文件名括起来,如下所示:

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

由于文件名内部无需更改,因此可以直接应用于变量:

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

外部引号 (") 由本地 shell 解释。内部引号 (\") 在远程服务器上进行解释。感谢@chepner 指出参数是如何处理两次的。