How Do I Escape Spaces in Paths for Scp in Linux?

The Secure Copy tool (scp) is an easy way to securely copy files to and from remote computers. But frustration can easily set in when scp does not work correctly due to spaces in file names and/or folder paths.

In this tutorial, we will show you 3 ways to avoid scp errors arising from having spaces in path names.

Escape Spaces in Path Names for Scp Command

The following image shows a familiar error that is encountered when using the scp command with spaces in file or folder names.

Scp Error with Spaces in Path Names
Scp Error with Spaces in Path Names

All I am trying to do is copy a single file named file 1.txt which is contained in a folder named big data and a subfolder named sales records.

Let us look at how to avoid such errors.

1. Escape Spaces with Backslash in Scp

The first method to escape spaces in paths when using the scp command is to add a backslash (\) right in front of each space.

Here is an example.

$ scp big\ data/sales\ records/file\ 1.csv shola@20.56.105.164:/home/shola
Escape Spaces with Backslash for Scp
Escape Spaces with Backslash for Scp

2. Escape Spaces with Quotation Marks in Scp

The second way to avoid scp errors due to spaces in path names is to enclose the entire path name in quotation marks (""). This works with either double quotes or single quotes.

For example:

$ scp "big data/sales records/file 1.csv" shola@20.56.105.164:/home/shola
OR
$ scp 'big data/sales records/file 1.csv' shola@20.56.105.164:/home/shola
Escape Spaces with Double Quotation for Scp
Escape Spaces with Double Quotation for Scp
Escape Spaces with Single Quotation for Scp
Escape Spaces with Single Quotation for Scp

3. Escape Spaces with Both Backslash and Quotation in Scp

The third method of escaping spaces in path names is by combining backslash and quotation marks. This is especially important when copying files from a remote computer.

Here is an example.

$ scp "shola@20.56.105.164:/home/shola/file\ 1.csv" "big data/sales records"
Escape Spaces with Backslash and Quotation for Scp
Escape Spaces with Backslash and Quotation for Scp
Conclusion

In this tutorial, we have described 3 ways in which you can avoid scp errors due to spaces in path names. The first method is to add a backslash in front of spaces while the second method is to use quotation marks around the pathname. The third method is to combine backslash and quotation marks.

Got something to say? Join the discussion.