The simplest way to copy directories recursively with SCP is by using the -r (recursive) flag. This works similarly to the recursive flag in commands like cp or rsync.
scp -r /local/directory user@remotehost:/remote/directory
For large directories, consider these optimizations:
scp -rpC /local/large_dir user@remote:/backup/
Where:
-ppreserves modification times-Cenables compression
For better performance with many small files:
tar czf - /local/directory | ssh user@remote "tar xzf - -C /remote/directory"
To maintain file attributes during recursive copy:
scp -rp /local/dir user@remote:/remote/
Note that preserving ownership (-o) typically requires root privileges.
Hidden Files: SCP with -r will copy hidden files (starting with .) by default.
Symlinks: Use -L to follow symbolic links:
scp -rL /local/linked_dir user@remote:/remote/
The scp (Secure Copy Protocol) command is a powerful tool for transferring files between hosts over SSH. While many users know it for single-file transfers, its recursive directory copying feature is equally important for efficient file management.
To copy an entire directory with all its contents, use the -r (recursive) flag:
scp -r /local/directory user@remotehost:/remote/directory
Here are some common scenarios with detailed commands:
Copying Local Directory to Remote Server
scp -r ~/projects/my_app user@example.com:/home/user/applications/
Copying Remote Directory to Local Machine
scp -r user@example.com:/var/logs/ /local/backup/
Preserving File Attributes
For maintaining original timestamps and permissions:
scp -rp ~/data user@backup-server:/storage/
Combine recursive copy with other useful flags:
scp -rP 2222 -C ~/large_dir user@alt-host:/destination/
This command uses port 2222 (-P) and compression (-C).
When dealing with recursive copies, you might encounter:
- Permission errors (use
sudoor check remote permissions) - Hidden files not copying (ensure your command includes dotfiles)
- Connection timeouts (try
-o ConnectTimeout=30)
For more advanced recursive transfers, consider rsync:
rsync -avz -e ssh /local/dir/ user@remote:/remote/dir/
This provides better progress tracking and partial transfer resumption.