I encountered similar issues when trying to copy files from remote paths containing spaces using scp
from within a Bash script.
Here are the solutions I came up with:
Escape paths manually:
scp user@host:'dir\ with\ spaces/file\ with\ spaces' <destination>
scp user@host:"dir\\ with\\ spaces/file\\ with\\ spaces" <destination>
scp user@host:dir\\\ with\\\ spaces/file\\\ with\\\ spaces <destination>
Note: does not require option -T
(see below).
Use double-quoting + option -T
:
scp -T user@host:"'path with spaces'" <destination>
scp -T user@host:'"path with spaces"' <destination>
scp -T user@host:"\"path with spaces\"" <destination>
Note: without option -T
, these commands fail with protocol error: filename does not match request
. The reason for this is discussed in detail here.
Escape path using Bash's printf:
source="path with spaces"
printf -v source "%q" "${source}"
scp user@host:"${source}" <destination>
One-liner for shell use:
source="path with spaces"; printf -v source "%q" "${source}"; scp user@host:"${source}" <destination>
Note: works fine without option -T
.