How do I copy a folder from remote to local using scp?

To copy a folder (directory) from a remote server to your local machine using scp, use the -r (recursive) flag. Here’s the command structure and examples:

Basic Syntax

scp -r <username>@<remote-host>:<remote-folder-path> <local-destination-path>
  • -r: Recursively copy directories and their contents.
  • <username>: Your remote server username (e.g., ubuntu, root).
  • <remote-host>: IP address or domain of the remote server (e.g., 123.45.67.89, example.com).
  • <remote-folder-path>: Path to the folder on the remote server.
  • <local-destination-path>: Local directory where the folder will be saved.

Example

Copy the remote folder /home/user/projects to your local ~/Downloads directory:

scp -r user@example.com:/home/user/projects ~/Downloads

Notes

  1. Specify a Port (if SSH uses a non-default port, e.g., 2222):
   scp -r -P 2222 user@example.com:/remote/folder ~/local/path
  1. Preserve File Metadata (timestamps, permissions):
   scp -rp user@example.com:/remote/folder ~/local/path
  1. Compress Files During Transfer (faster for large folders):
   scp -rC user@example.com:/remote/folder ~/local/path

Common Errors & Fixes

  • Permission Denied: Ensure you have read access to the remote folder and write access to the local destination.
  • Missing -r Flag: Without -r, scp will skip directories.
  • SSH Key Authentication: If using SSH keys, ensure your key is added to the SSH agent (ssh-add ~/.ssh/your_key).

Verify the Transfer

Check the copied folder locally:

ls -l ~/Downloads/projects  # Replace with your local path

Leave a Reply

Your email address will not be published. Required fields are marked *