Trouble in script with spaces in filename

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.

Code:

PATH=/var/root/Documents/MyFile OG-v1.2.3.pkg
scp $PATH <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8fc2eacfbebfa1bea1bebfa1bcbc">[email protected]</a>:/Users/Me/Desktop

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

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You should quote both the declaration and the usage

path="/var/root/Documents/MyFile OG-v1.2.3.pkg"
scp "$path" <a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0f426a4f3e3f213e213e3f213c3c">[email protected]</a>:/Users/Me/Desktop

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.)

Method 2

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x