I've got a script that scp's a file from remote host back to local. Sometimes the file names contain spaces. scp does not like spaces in its file names. For some reason my attempts at handling the spaces have not resulted in the correct scp path.


PATH=/var/root/Documents/MyFile OG-v1.2.3.pkg
scp $PATH Me@

Results in

Cannot find directory: var/root/Documents/MyFile
Cannot find directory: OG-v1.2.3.pkg

Enclosing PATH in quotes "$PATH" gives the same error.

Swapping the spaces for escaped spaces also is not working, although as far as I can tell it should:

ESC_PATH=${PATH/' '/'\ '}

although printing the escaped path shows that the edit worked:

echo $ESC_PATH
> /var/root/Documents/MyFile\ OG-v1.2.3.pkg
  • 4
    Please do not use $PATH for your own variables, because your terminal needs it.
    – Bernhard
    Jul 13 '14 at 8:48

You should quote both the declaration and the usage

path="/var/root/Documents/MyFile OG-v1.2.3.pkg"
scp "$path" Me@

If you do not quote the first, $path will contain just the first part. If you do not quote the second, scp will treat each space-separated part as an argument.

(I've changed $PATH to $path because $PATH is an important reserved variable and you must not use it for general purposes.)

  • 1
    Perfect! Thank's a million @Matteo. Turns out there was also a prefixed space throwing a wrench into it as well. Dec 7 '12 at 23:04

I was trying something very similar with ssh and passing a command line through it. e.g.

ssh <somehost> ls -l "$PATH"

I found that simply defining "$PATH" didn't do the trick - it still threw up errors. However if I ran

ssh <somehost> ls -l "\"$PATH"\"

This worked. The trick is to ensure an additional set of " " gets passed to the ssh command from the shell.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.