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
- Specify a Port (if SSH uses a non-default port, e.g.,
2222):
scp -r -P 2222 user@example.com:/remote/folder ~/local/path
- Preserve File Metadata (timestamps, permissions):
scp -rp user@example.com:/remote/folder ~/local/path
- 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
-rFlag: Without-r,scpwill 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