SyntaxStudy
Sign Up
Linux / Bash File Transfer with scp and rsync
Linux / Bash Beginner 1 min read

File Transfer with scp and rsync

SSH provides two main tools for secure file transfer. `scp` (secure copy) works like `cp` but over SSH. It is simple and familiar but transfers files as a flat copy without comparing existing content. For large transfers or synchronisation tasks, `rsync` is far more efficient because it only transfers the differences between source and destination. `rsync` builds a delta algorithm that compares file checksums and sizes, sending only the changed blocks. With the `-a` (archive) flag, it preserves permissions, timestamps, symbolic links, and ownership. The `--delete` flag removes files from the destination that no longer exist at the source, making it suitable for true directory synchronisation. The `-z` flag compresses data during transfer. The `--dry-run` or `-n` flag for `rsync` shows what would be transferred without making any changes — always recommended before a large sync or one that uses `--delete`. Adding `-v` or `--progress` shows per-file progress. `rsync` can also synchronise between two local directories, making it useful for local backups as well as remote transfers.
Example
# ---- scp: secure copy ----

# Copy a local file to remote server
scp report.pdf alice@server.example.com:/home/alice/

# Copy remote file to local directory
scp alice@server.example.com:/var/log/app.log /tmp/

# Copy a directory recursively
scp -r /local/project/ alice@server.example.com:/home/alice/

# Use a specific port
scp -P 2222 file.txt alice@server.example.com:/tmp/

# Use a specific identity file
scp -i ~/.ssh/aws.pem file.txt ec2-user@ec2-host:/tmp/

# ---- rsync: efficient file synchronisation ----

# Sync local dir to remote (archive mode)
rsync -av /local/project/ alice@server.example.com:/home/alice/project/

# Dry run — show what would be transferred
rsync -av --dry-run /local/data/ remote:/data/

# Sync with deletion (mirror source exactly)
rsync -av --delete /local/project/ alice@server:/home/alice/project/

# Compress during transfer
rsync -avz /large/data/ alice@server:/data/

# Show progress for each file
rsync -av --progress /local/dir/ alice@server:/remote/dir/

# Exclude patterns
rsync -av --exclude='*.tmp' --exclude='.git/' \
    /local/project/ alice@server:/home/alice/project/

# Sync over a non-standard SSH port
rsync -av -e "ssh -p 2222" /local/dir/ alice@server:/remote/dir/

# Local backup (rsync between two local directories)
rsync -av --delete /home/alice/ /mnt/backup/alice/

# Scheduled rsync backup (add to crontab)
# 0 2 * * * rsync -az --delete /home/ /mnt/backup/home/