πŸ’‘
⚑
⌨
πŸ”§
🐧
Intermediate Bash July 19, 2025 luc

rsync Command Linux Daily Tip – Professional File Synchronization

Categories: Command Line
Tags: #rrsync
rsync Command Linux Daily Tip – Professional File Synchronization

Command / Code

Bash Main Command
rsync -avh --progress /home/user/documents/ /backup/documents/

Description

How to Use rsync Command in Linux?

Quick Answer: Use rsync -avh source/ destination/ to synchronize files efficiently in Linux. The rsync command only transfers differences between files, making it perfect for backups and file synchronization with minimal bandwidth usage.

Essential rsync Commands (Copy & Paste Ready)

# Basic local sync with progress
rsync -avh --progress /home/user/docs/ /backup/docs/

# Remote backup via SSH
rsync -avz -e ssh /var/www/ user@server:/backup/

# Test sync without making changes
rsync -avh --dry-run /source/ /destination/

# Mirror sync (delete extra files)
rsync -avh --delete /source/ /destination/

# Resume interrupted transfer
rsync -avh --partial --progress /files/ user@remote:/dest/

Frequently Asked Questions

What does rsync -avh mean?

Answer: rsync -avh combines archive mode (-a) for preserving permissions, verbose output (-v) to show progress, and human-readable sizes (-h) for easy reading. It’s the most common rsync command combination.

Is rsync faster than cp command?

Answer: Yes, rsync is faster for updates because it only transfers changed portions of files, while cp copies entire files. For initial copies, cp might be slightly faster locally.

How do I backup files with rsync?

Answer: Use rsync -avh --progress /source/ /backup/ for local backups or rsync -avz -e ssh /local/ user@server:/remote/ for remote backups via SSH.

What’s the difference between /source and /source/?

Answer: /source/ copies the contents of the source directory, while /source copies the directory itself. Always use trailing slashes for consistent behavior.

How do I exclude files in rsync?

Answer: Use --exclude='pattern' to skip specific files. Example: rsync -avh --exclude='*.tmp' --exclude='logs/' /source/ /dest/ excludes temporary files and logs directory.

Can rsync resume interrupted transfers?

Answer: Yes, use rsync -avh --partial --progress to keep partially transferred files and resume them on the next sync attempt.

What is rsync Command in Linux?

The rsync (remote sync) command is a powerful file synchronization tool that efficiently transfers and synchronizes files between directories or systems. Unlike basic copy commands, rsync only transfers the differences between files, making it incredibly fast for large datasets and remote operations.

How to Use rsync Step by Step?

  1. Basic local sync: rsync -avh /source/ /destination/
  2. Remote backup: rsync -avz /local/ user@server:/remote/
  3. Test first: rsync -avh --dry-run /source/ /dest/
  4. Verify results: Check destination directory for synchronized files

How to Set Up Remote rsync Backup?

  1. Generate SSH key: ssh-keygen -t rsa -b 4096
  2. Copy key to server: ssh-copy-id user@backup-server
  3. Test connection: ssh user@backup-server
  4. Run initial backup: rsync -avz /local/ user@backup-server:/backup/
  5. Verify files: Check remote directory for transferred files

What are the Most Important rsync Command Examples?

Basic rsync Operations

TaskCommandDescription
Local backuprsync -avh /source/ /backup/Copy with progress display
Remote backuprsync -avz user@server:/remote/ /local/Download from remote server
Upload to serverrsync -avz /local/ user@server:/remote/Upload to remote server
Mirror syncrsync -avh --delete /source/ /dest/Exact copy, delete extra files
Test runrsync -avh --dry-run /source/ /dest/Preview without changes

Basic File Synchronization

# Local directory sync with progress
rsync -avh --progress /home/user/documents/ /backup/documents/

# Remote server backup via SSH
rsync -avz -e ssh /var/www/ user@backup-server:/backups/website/

# Sync with file deletion (mirror)
rsync -avh --delete /source/ /destination/

Advanced rsync Operations

# Test sync without making changes
rsync -avh --dry-run --delete /source/ /destination/

# Exclude specific files and directories
rsync -avh --exclude='*.tmp' --exclude='cache/' /data/ /backup/

# Resume interrupted transfers
rsync -avh --partial --progress /large-files/ user@remote:/destination/

# Bandwidth-limited sync
rsync -avh --bwlimit=1000 /data/ user@remote:/backup/

What are the Most Important rsync Command Options?

OptionDescriptionUse Case
-aArchive mode (preserves permissions, timestamps)Standard backups
-vVerbose outputMonitor transfer progress
-hHuman-readable file sizesEasy size reading
-zCompress data during transferRemote/slow connections
--deleteRemove files not in sourceMirror synchronization
--progressShow transfer progressMonitor large transfers
--partialKeep partial files for resumeUnreliable connections
--dry-runTest without making changesVerify before sync
--excludeSkip files matching patternSelective synchronization

When Should You Use rsync Command?

Common rsync Scenarios

ScenarioBest CommandWhy Use rsync
Daily backupsrsync -avh --delete /data/ /backup/Only transfers changes
Website deploymentrsync -avz --exclude='.git/' /local/ user@server:/var/www/Fast, excludes unnecessary files
Large file syncrsync -avh --partial --progress /files/ /dest/Resumable transfers
Database backuprsync -avh /var/lib/mysql/ /backup/mysql/Preserves permissions
Cross-server migrationrsync -avz -e ssh /old-server/ user@new-server:/Secure remote transfer

How to Create Automated rsync Backup?

  1. Create backup script: nano /usr/local/bin/backup.sh
  2. Add rsync command: rsync -avh --delete /important/ /backup/
  3. Make executable: chmod +x /usr/local/bin/backup.sh
  4. Test script: /usr/local/bin/backup.sh
  5. Add to crontab: crontab -e
  6. Schedule daily: 0 2 * * * /usr/local/bin/backup.sh

Website Deployment

# Deploy with backup of previous version
rsync -avh --backup --backup-dir=/backup/previous-$(date +%Y%m%d) /staging/ /var/www/html/

Database Backup

# MySQL data directory backup
rsync -avh --inplace /var/lib/mysql/ /backup/mysql-$(date +%Y%m%d)/

Automated Backup Script

#!/bin/bash
# Daily backup with logging
rsync -avh --delete --log-file=/var/log/backup.log /important-data/ /backup/daily/

How to Fix Common rsync Problems?

Step-by-Step rsync Troubleshooting

Problem: Permission denied errors

  1. Check file permissions: ls -la /source/
  2. Verify SSH access: ssh user@remote-server
  3. Use sudo if needed: sudo rsync -avh /source/ /dest/
  4. Fix ownership: sudo chown -R user:group /destination/

Problem: Slow transfer speeds

  1. Add compression: Use -z flag for remote transfers
  2. Limit bandwidth: rsync -avh --bwlimit=1000 /source/ /dest/
  3. Check network: ping remote-server and traceroute remote-server
  4. Use different SSH cipher: rsync -avz -e "ssh -c aes128-ctr" /local/ user@server:/remote/

Problem: Files not syncing as expected

  1. Test with dry-run: rsync -avh --dry-run /source/ /dest/
  2. Check trailing slashes: Ensure consistent /source/ format
  3. Verify exclude patterns: Remove --exclude temporarily
  4. Check available space: df -h /destination/

rsync Error Codes Reference

Exit CodeMeaningCommon Cause
0SuccessTransfer completed successfully
1Syntax errorInvalid command syntax
2Protocol incompatibilityVersion mismatch
3File selection errorsPermission issues
5Starting transfer errorConnection problems
10Socket I/O errorNetwork connectivity
11File I/O errorDisk space or permissions
23Partial transferSome files couldn’t transfer

What are the Best rsync Pro Tips?

  1. Always test first: Use --dry-run to preview operations before execution
  2. Trailing slash matters: /source/ syncs contents, /source syncs the directory itself
  3. Monitor with stats: Add --stats for detailed transfer information
  4. Schedule with cron: Automate regular backups using crontab
  5. Log operations: Use --log-file for audit trails and troubleshooting

How Does rsync Compare to Other Commands?

CommandSpeedFeaturesBest For
cpFast locallyBasic copySimple local copies
scpSlowerSecure remote copyOne-time remote transfers
rsyncFastest for updatesIncremental, resumableBackups, synchronization

What are the Best rsync Command Templates?

Quick Copy-Paste rsync Commands

PurposeCommand TemplateNotes
Basic backuprsync -avh --progress /source/ /backup/Local backup with progress
Remote backuprsync -avz -e ssh /local/ user@server:/remote/SSH with compression
Mirror syncrsync -avh --delete /source/ /destination/Exact copy, removes extra files
Safe testrsync -avh --dry-run --delete /source/ /dest/Preview changes only
Resume transferrsync -avh --partial --progress /files/ /dest/Continue interrupted transfers
Exclude filesrsync -avh --exclude='*.tmp' /source/ /dest/Skip temporary files
Bandwidth limitrsync -avh --bwlimit=1000 /source/ /dest/Limit to 1MB/s

How to Perform Safe rsync Operation?

  1. Plan the sync: Identify source and destination directories
  2. Test first: rsync -avh --dry-run /source/ /destination/
  3. Review output: Check which files will be transferred/deleted
  4. Backup destination: cp -r /destination/ /destination-backup/
  5. Run actual sync: rsync -avh --progress /source/ /destination/
  6. Verify results: diff -r /source/ /destination/
  7. Monitor logs: Check for any error messages or warnings

Mastering the rsync command is essential for efficient file management in Linux. Whether you’re backing up data, deploying websites, or synchronizing directories, rsync provides the speed and reliability needed for professional system administration tasks.


Complete rsync Troubleshooting Guide

How to Diagnose rsync Connection Issues?

SSH Connection Problems

  1. Test SSH connection: ssh user@remote-server
  2. Check SSH key: ssh-add -l to list loaded keys
  3. Verify key on server: cat ~/.ssh/authorized_keys on remote
  4. Test with password: rsync -avz -e "ssh -o PasswordAuthentication=yes" /local/ user@server:/remote/
  5. Check SSH config: Review /etc/ssh/ssh_config and ~/.ssh/config

Network and Firewall Issues

  1. Test connectivity: ping remote-server
  2. Check ports: telnet remote-server 22
  3. Verify firewall: sudo ufw status or sudo iptables -L
  4. Test different port: rsync -avz -e "ssh -p 2222" /local/ user@server:/remote/

What to Do When rsync Fails?

Disk Space Problems

IssueCommand to CheckSolution
Source fulldf -h /source/Free up space or use different source
Destination fulldf -h /destination/Clean destination or use larger drive
Temp space fulldf -h /tmp/Clean /tmp or set TMPDIR variable
Inode exhaustiondf -i /destination/Delete unnecessary files or directories

Permission and Ownership Issues

  1. Check current permissions: ls -la /path/to/file
  2. Fix source permissions: sudo chmod -R 755 /source/
  3. Fix destination ownership: sudo chown -R user:group /destination/
  4. Use numeric IDs: rsync -avh --numeric-ids /source/ user@server:/dest/
  5. Skip permission errors: rsync -rlptgoD --no-perms /source/ /dest/

How to Fix rsync Performance Issues?

Slow Transfer Optimization

  1. Enable compression: Add -z flag for remote transfers
  2. Optimize SSH: rsync -avz -e "ssh -c aes128-ctr -o Compression=no" /local/ user@server:/remote/
  3. Increase buffer size: rsync -avz --sockopts=SO_SNDBUF=65536,SO_RCVBUF=65536 /local/ user@server:/remote/
  4. Use multiple connections: Split large transfers into parallel jobs
  5. Check network bandwidth: iperf3 -c remote-server

Memory and CPU Issues

ProblemSymptomSolution
High memory usageSystem slow, swap usageUse --max-size=1G to limit file sizes
High CPU usage100% CPU utilizationAdd nice -n 10 rsync... for lower priority
Too many files“Argument list too long”Use --files-from with file list
Large directoriesVery slow startupUse --no-inc-recursive for faster listing

Advanced rsync Troubleshooting

Handling Special Characters and File Names

  1. Unicode issues: rsync -avz --iconv=utf-8 /source/ /dest/
  2. Space in names: Use quotes: rsync -avz "/path with spaces/" /dest/
  3. Special characters: rsync -avz --protect-args /source/ /dest/
  4. Case sensitivity: rsync -avz --ignore-case /source/ /dest/

Debugging rsync Operations

# Enable verbose debugging
rsync -avvvz --debug=ALL /source/ user@server:/dest/

# Log to file for analysis
rsync -avz --log-file=/var/log/rsync.log /source/ /dest/

# Show statistics
rsync -avz --stats --human-readable /source/ /dest/

# Monitor with progress and itemization
rsync -avz --progress --itemize-changes /source/ /dest/

Common Error Messages and Solutions

Error MessageCauseFix
“rsync: connection unexpectedly closed”Network interruptionRetry with --partial flag
“rsync error: some files/attrs were not transferred”Permission issuesCheck file permissions and ownership
“rsync: failed to connect to server”SSH/connection problemVerify SSH keys and network connectivity
“rsync: recv_generator: mkdir failed”Directory creation failedCheck destination permissions
“file has vanished”Source file deleted during syncNormal for active filesystems
“IO error encountered”Hardware/filesystem issueCheck disk health with fsck

Emergency rsync Recovery Procedures

Recovering from Failed Transfers

  1. Resume partial transfer: rsync -avz --partial /source/ /dest/
  2. Check for corrupted files: rsync -avz --checksum /source/ /dest/
  3. Verify integrity: find /dest/ -name "*.rsync-partial" -delete
  4. Compare directories: diff -r /source/ /dest/
  5. Force complete re-sync: rsync -avz --ignore-times /source/ /dest/

Data Recovery Best Practices

  1. Always backup before major syncs: cp -r /dest/ /dest-backup/
  2. Use version control: rsync -avz --backup --backup-dir=/backups/$(date +%Y%m%d) /source/ /dest/
  3. Test on small dataset first: Verify process works before full sync
  4. Monitor disk space: Ensure adequate space throughout process
  5. Keep logs: --log-file for audit trail and debugging

Complete rsync Troubleshooting Guide

How to Diagnose rsync Connection Issues?

SSH Connection Problems

  1. Test SSH connection: ssh user@remote-server
  2. Check SSH key: ssh-add -l to list loaded keys
  3. Verify key on server: cat ~/.ssh/authorized_keys on remote
  4. Test with password: rsync -avz -e "ssh -o PasswordAuthentication=yes" /local/ user@server:/remote/
  5. Check SSH config: Review /etc/ssh/ssh_config and ~/.ssh/config

Network and Firewall Issues

  1. Test connectivity: ping remote-server
  2. Check ports: telnet remote-server 22
  3. Verify firewall: sudo ufw status or sudo iptables -L
  4. Test different port: rsync -avz -e "ssh -p 2222" /local/ user@server:/remote/

What to Do When rsync Fails?

Disk Space Problems

IssueCommand to CheckSolution
Source fulldf -h /source/Free up space or use different source
Destination fulldf -h /destination/Clean destination or use larger drive
Temp space fulldf -h /tmp/Clean /tmp or set TMPDIR variable
Inode exhaustiondf -i /destination/Delete unnecessary files or directories

Permission and Ownership Issues

  1. Check current permissions: ls -la /path/to/file
  2. Fix source permissions: sudo chmod -R 755 /source/
  3. Fix destination ownership: sudo chown -R user:group /destination/
  4. Use numeric IDs: rsync -avh --numeric-ids /source/ user@server:/dest/
  5. Skip permission errors: rsync -rlptgoD --no-perms /source/ /dest/

How to Fix rsync Performance Issues?

Slow Transfer Optimization

  1. Enable compression: Add -z flag for remote transfers
  2. Optimize SSH: rsync -avz -e "ssh -c aes128-ctr -o Compression=no" /local/ user@server:/remote/
  3. Increase buffer size: rsync -avz --sockopts=SO_SNDBUF=65536,SO_RCVBUF=65536 /local/ user@server:/remote/
  4. Use multiple connections: Split large transfers into parallel jobs
  5. Check network bandwidth: iperf3 -c remote-server

Memory and CPU Issues

ProblemSymptomSolution
High memory usageSystem slow, swap usageUse --max-size=1G to limit file sizes
High CPU usage100% CPU utilizationAdd nice -n 10 rsync... for lower priority
Too many files“Argument list too long”Use --files-from with file list
Large directoriesVery slow startupUse --no-inc-recursive for faster listing

Advanced rsync Troubleshooting

Handling Special Characters and File Names

  1. Unicode issues: rsync -avz --iconv=utf-8 /source/ /dest/
  2. Space in names: Use quotes: rsync -avz "/path with spaces/" /dest/
  3. Special characters: rsync -avz --protect-args /source/ /dest/
  4. Case sensitivity: rsync -avz --ignore-case /source/ /dest/

Debugging rsync Operations

# Enable verbose debugging
rsync -avvvz --debug=ALL /source/ user@server:/dest/

# Log to file for analysis
rsync -avz --log-file=/var/log/rsync.log /source/ /dest/

# Show statistics
rsync -avz --stats --human-readable /source/ /dest/

# Monitor with progress and itemization
rsync -avz --progress --itemize-changes /source/ /dest/

Common Error Messages and Solutions

Error MessageCauseFix
“rsync: connection unexpectedly closed”Network interruptionRetry with --partial flag
“rsync error: some files/attrs were not transferred”Permission issuesCheck file permissions and ownership
“rsync: failed to connect to server”SSH/connection problemVerify SSH keys and network connectivity
“rsync: recv_generator: mkdir failed”Directory creation failedCheck destination permissions
“file has vanished”Source file deleted during syncNormal for active filesystems
“IO error encountered”Hardware/filesystem issueCheck disk health with fsck

Emergency rsync Recovery Procedures

Recovering from Failed Transfers

  1. Resume partial transfer: rsync -avz --partial /source/ /dest/
  2. Check for corrupted files: rsync -avz --checksum /source/ /dest/
  3. Verify integrity: find /dest/ -name "*.rsync-partial" -delete
  4. Compare directories: diff -r /source/ /dest/
  5. Force complete re-sync: rsync -avz --ignore-times /source/ /dest/

Data Recovery Best Practices

  1. Always backup before major syncs: cp -r /dest/ /dest-backup/
  2. Use version control: rsync -avz --backup --backup-dir=/backups/$(date +%Y%m%d) /source/ /dest/
  3. Test on small dataset first: Verify process works before full sync
  4. Monitor disk space: Ensure adequate space throughout process
  5. Keep logs: --log-file for audit trail and debugging

Detailed Explanation

The Linux command rsync -avh –progress /home/user/documents/ /backup/documents/ is used to synchronize files and directories between two locations, in this case from /home/user/documents/ to /backup/documents/. Here’s a breakdown of each component:

  • rsync: A powerful tool for copying and synchronizing files and directories, either locally or between remote systems. It efficiently transfers only the differences between source and destination, making it faster than a full copy.
  • -a (archive mode): Enables a set of options to preserve file attributes during the transfer, including:
    • File permissions
    • Timestamps
    • Symbolic links
    • Ownership
    • Group information
    • Recursively copies directories This ensures the destination files are as close as possible to the source in terms of metadata.
  • -v (verbose): Provides detailed output about the files being transferred, showing which files are being copied or skipped.
  • -h (human-readable): Formats file sizes in the output (e.g., KB, MB, GB) to be easier to read.
  • –progress: Shows the progress of each file transfer, including the percentage completed, transfer speed, and estimated time remaining.
  • /home/user/documents/: The source directory. The trailing slash (/) means rsync copies the contents of the documents directory, not the directory itself.
  • /backup/documents/: The destination directory where the files will be copied. If it doesn’t exist, rsync will create it.

What the Command DoesThis command copies all files and directories from /home/user/documents/ to /backup/documents/, preserving file attributes (permissions, timestamps, etc.), showing detailed output with progress information, and displaying file sizes in a human-readable format. If files already exist in the destination, rsync will only transfer the differences (e.g., updated or new files), making it efficient for backups or synchronization.Example OutputWhen you run the command, you might see something like:

building file list ... done
file1.txt
          1.00K 100%    1.19MB/s    00:00:00 (xfr#1, to-chk=99/100)
file2.txt
         10.00M 100%    5.00MB/s    00:00:02 (xfr#2, to-chk=98/100)
sent 10.01M bytes  received 92 bytes  2.00M bytes/sec
total size is 10.00M  speedup is 1.00

Notes

  • If you omit the trailing slash on the source (/home/user/documents), rsync will copy the documents directory itself into /backup/documents/documents/, which may not be what you want.
  • Ensure the destination path (/backup/documents/) has sufficient permissions and space.
  • Rsync is highly efficient for incremental backups, as it only transfers changes.

If you need more details or have a specific use case, let me know!

Related Commands

Tip Actions

Quick Actions