Introduction
Executing rsync with the --delete flag without dry-run validation is one of the fastest ways to wipe production data. When --delete is active, rsync forces the destination directory to match the source directory exactly, which means any file present on the destination but absent from the source will be unlinked immediately. A missing trailing slash, an unmounted source disk, or an unexpected filter rule will cause rsync to view the target directory as polluted, resulting in mass deletions before you can cancel the process with Ctrl+C.
This guide covers the internal mechanics of rsync file deletion, the exact syntax traps that cause unintended data destruction, how to parse itemized dry runs, and how to use cryptographic checksums to confirm transfer integrity across local and remote filesystems.
+-------------------------------------------------------------------------------+| SOURCE DIRECTORY || /srv/data/ (contains: app.log, config.json, db.sqlite) |+-------------------------------------------------------------------------------+ | rsync -av --delete /srv/data /mnt/backup/ | v+-------------------------------------------------------------------------------+| DESTINATION DIRECTORY || /mnt/backup/ || ├── data/ <-- Created because source lacked trailing slash || │ ├── app.log || │ ├── config.json || │ └── db.sqlite || └── [DELETED FILES] <-- All previous backups in /mnt/backup/ wiped instantly|+-------------------------------------------------------------------------------+The Trailing Slash: Root Cause of Most Deletion Disasters
The single most common cause of accidental deletion with rsync is the trailing slash on the source path. In POSIX file path conventions, a trailing slash is often optional or normalized away by utilities like cp or mv. In rsync, however, a trailing slash dictates whether the directory itself or only its contents are sent across the wire.
When you omit the trailing slash on the source:
rsync -av --delete /var/www/site /mnt/backups/site/rsync interprets /var/www/site as the object to transfer. It creates a subfolder named site inside /mnt/backups/site/, resulting in the path /mnt/backups/site/site/. Because you passed the --delete flag, rsync inspects the destination root (/mnt/backups/site/). It finds existing files from previous correct sync operations, identifies that they do not match the incoming single directory entry named site, and deletes every single existing file in /mnt/backups/site/.
When you include the trailing slash on the source:
rsync -av --delete /var/www/site/ /mnt/backups/site/The trailing slash instructs rsync to copy the contents of /var/www/site/ directly into /mnt/backups/site/. The directory structure matches 1:1, and only files legitimately removed from the source are pruned from the destination.
Trailing Slash Matrix
| Source Path Syntax | Destination Path | Resulting Destination Path | Effect of --delete |
|---|---|---|---|
/srv/media (No slash) | /mnt/storage | /mnt/storage/media/ | Deletes everything in /mnt/storage/ except media/ |
/srv/media/ (With slash) | /mnt/storage | /mnt/storage/ | Deletes files in /mnt/storage/ missing from /srv/media/ |
/srv/media (No slash) | /mnt/storage/media | /mnt/storage/media/media/ | Deletes all files directly under /mnt/storage/media/ |
/srv/media/ (With slash) | /mnt/storage/media | /mnt/storage/media/ | Proper 1:1 mirror; deletes only obsolete items |
To protect against this behavior, explicitly test path normalization in automated environments. Avoid dynamically generating source paths without ensuring trailing slash consistency.
Deletion Phases: How and When rsync Prunes Files
The --delete flag does not have a single mode of operation. By default, rsync deletes files during the file transfer process, but you can control the timing using specific phase flags. Misunderstanding when deletions occur can lead to broken intermediate states or out-of-space conditions.
rsync Source -> Scan -> Transfer -> Delete Phase -> Done1. --delete-during (Default Behavior in Modern rsync)
When using --delete in rsync 3.x, the utility defaults to --delete-during. As the generator scans the directory tree and finds discrepancies, it unlinks destination files incrementally while copying new data.
Advantage: Minimizes disk footprint on the target filesystem because space is reclaimed continuously during the run.
Risk: If the sync aborts halfway through (network drop or terminal interruption), the destination contains a mixture of deleted old files and unwritten new files, leaving the target in an inconsistent state.
2. --delete-before
Forces rsync to perform a complete scan of the source and destination trees, delete every unlinked file on the destination, and only then begin copying changed files.
rsync -av --delete-before /srv/app/ /mnt/backup/app/Advantage: Ensures that destination disk capacity is freed up completely before any new bytes are transferred. This is critical when writing to a disk that is near 100% capacity.
Risk: If the source is corrupted or empty due to an unmounted partition, rsync wipes the destination first, then fails to read the source, leaving you with zero files.
3. --delete-after
Instructs rsync to transfer all updated and new files first, write them to temporary files on the target, rename them into place, and only prune removed files at the very end of the run.
rsync -av --delete-after /srv/app/ /mnt/backup/app/Advantage: Highly resilient against transient network drops. If the transfer fails midway, the existing destination files remain available and intact until the next run completes.
Risk: Requires sufficient free disk space to store both the incoming updates and the old files slated for deletion simultaneously.
4. --delete-excluded
By default, if you tell rsync to exclude a pattern using --exclude="*.log", rsync ignores those files on both ends. It will not copy them, and it will not delete them from the destination if they already exist there.
Adding --delete-excluded changes this behavior:
rsync -av --delete --delete-excluded --exclude="*.log" /srv/app/ /mnt/backup/app/Any file matching *.log on the target will be permanently deleted, even though it was explicitly excluded from the transfer. This flag frequently causes accidental loss of log archives and environment configuration files (.env).
Step 1: Mandatory Dry-Run Verification
Never run a command containing --delete without running a simulation first. The simulation must output enough information to differentiate between normal file synchronization and catastrophic bulk deletion.
The Standard Dry-Run Command
Combine -n (or --dry-run) with itemized logging:
rsync -avhn --delete --itemize-changes /srv/data/ /mnt/backup/data/The flag breakdown:
-a: Archive mode (recurses directories, preserves symlinks, permissions, modification times, group, owner, and device/special files).-v: Verbose output.-h: Human-readable numbers.-n: Dry-run mode. Performs all checks and disk traversals without writing, updating, or deleting any files.--itemize-changes(-i): Outputs a 11-character code per file detailing exactly why rsync intends to touch that file.
ITEMIZE CHANGE STRING >f.st...... ||||||||||| Transfer direction --+|||||||||| File type ---+||||||||| Checksum changed --+|||||||| Size changed ---+||||||| Modification time changed ----+|||||| Metadata changes -----++++++ (perms, owner, group, etc.)Decoding Itemize Changes Output
When inspecting dry-run logs, grep specifically for deletion events:
rsync -avhn --delete -i /srv/data/ /mnt/backup/data/ | grep '\*deleting'If the itemize output starts scrolling with hundreds of *deleting lines when you only modified three files, stop immediately. That is the indicator that your source path syntax is wrong or your source mount point is missing.
Here is how to decode the 11 characters output by -i:
Format: YXcstpoguax path/to/file-
Y (Update Type):
<: File is being sent to the remote host.>: File is being received from the remote host or transferred locally.c: Local change or file creation (e.g., directory creation or symlink update).h: Hard link created..: Item is not being updated (attributes may be updated).*: Signifies an event like*deleting.
-
X (File Type):
f: File.d: Directory.L: Symlink.D: Device node.S: Special file (FIFO, unix socket).
-
Subsequent Positions:
c: Checksum discrepancy (requires-cmode) or file creation.s: Size differs.t: Timestamp differs.p: Permissions differ.o: Owner differs.g: Group differs.u: Reserved for future use.a: ACL differs.x: Extended attributes differ.
A line reading:
>f.st...... etc/nginx/nginx.confindicates a regular file (f) where the size (s) and modification time (t) differ from the target, so it will be overwritten.
A line reading:
*deleting var/lib/mysql/ibdata1indicates that the database file exists on the target but not the source, and will be unlinked immediately upon execution without -n.
Step 2: Checksum Verification Over Size and Modification Times
By default, rsync uses a “quick check” algorithm. It compares only two metadata attributes for every candidate file:
- File size in bytes.
- Last modification timestamp (
mtime).
If both the size and the modification time match between the source and destination, rsync concludes that the file is identical and skips it. This optimization works across millions of files, but it has severe failure modes.
When Quick Check Fails
File A: Size = 4096 bytes, mtime = 12:00:00 -> [Block data altered by bit rot]File B: Size = 4096 bytes, mtime = 12:00:00 -> [Original data]rsync quick check result: MATCH (Corrupted file is never synced or repaired)- Silent Bit Rot and Data Corruption: If storage hardware suffers bad sectors or bit rot on the destination, the file content changes while the file size and
mtimeremain unchanged. A normal rsync run skips this file, leaving corrupted data on your backup. - Script Ingestion with Preserved Timestamps: Deployment pipelines or build scripts that unpack tarballs often restore the original timestamps (
tar -mvstar -p). If a script modifies a binary in place without altering its size, and backdates the timestamp, rsync ignores it. - Filesystem Timestamp Incompatibilities: Transferring data between an ext4 system (nanosecond precision) and a FAT32 or exFAT filesystem (2-second precision) causes false positives. Either rsync retransfers every file, or it misses updates due to timestamp truncation.
Forcing Cryptographic Checksums with -c
To force rsync to read the entire file and compute a rolling digest (MD5 or MD4 depending on the rsync version and compilation flags), use the -c or --checksum flag:
rsync -avhc -n --delete /srv/data/ /mnt/backup/data/When -c is passed:
- rsync scans the directory structure.
- It generates a 128-bit checksum for every file on the source.
- It requests or generates a checksum for the corresponding file on the destination.
- If the checksums match, the file is skipped, regardless of whether the modification timestamps differ.
- If the checksums differ, the file is queued for transfer, even if the size and
mtimeare identical.
+--------------------------------------------------------------------------+| PERFORMANCE IMPACT: QUICK CHECK VS CHECKSUM |+--------------------------------------------------------------------------+| Mode: Quick Check (Default) || Disk Activity: Read file metadata only (stat calls). Disk I/O is minimal.|| Speed: Up to 500,000 files/sec on fast NVMe storage. |+--------------------------------------------------------------------------+| Mode: Checksum (-c) || Disk Activity: Reads EVERY byte of EVERY file on BOTH filesystems. || Speed: Strictly limited by storage read throughput and CPU hashing. |+--------------------------------------------------------------------------+Quantifying the Trade-Off
Using -c turns an I/O operation that is metadata-bound into an operation that is read-throughput-bound.
On a 4 TB array containing 2,000,000 files:
- Quick check finishes the directory traversal in approximately 12 to 30 seconds.
- Checksum verification reads 4 TB from the source and 4 TB from the target. At a sustained sequential read rate of 500 MB/s per disk pool, the scan takes a minimum of 2.2 hours before transferring a single byte.
Best Practice: Run the default quick check for hourly or daily synchronization tasks. Schedule a separate weekly or monthly verification job using rsync -avc --delete to audit the backup for bit rot and silent divergence.
Real-World Simulation: Anatomy of a Disastrous Sync
To observe how quickly --delete destroys unlinked files, we can create a temporary sandbox on a Linux workstation.
Setting Up the Sandbox
Run this script in an empty directory to create two separate trees: a simulated live application directory and an existing backup target.
#!/usr/bin/env bashset -euo pipefail
# Create isolated directoriesrm -rf /tmp/rsync-testmkdir -p /tmp/rsync-test/sourcemkdir -p /tmp/rsync-test/destination
# Populate sourceecho "database-data" > /tmp/rsync-test/source/db.sqlecho "app-configuration" > /tmp/rsync-test/source/config.yml
# Populate destination with valid files and historical backupsmkdir -p /tmp/rsync-test/destination/historical_archiveecho "old-data-2025" > /tmp/rsync-test/destination/historical_archive/backup.tar.gzecho "app-configuration" > /tmp/rsync-test/destination/config.ymlecho "database-data" > /tmp/rsync-test/destination/db.sqlConfirm the initial layout:
$ tree /tmp/rsync-test//tmp/rsync-test/├── destination│ ├── config.yml│ ├── db.sql│ └── historical_archive│ └── backup.tar.gz└── source ├── config.yml └── db.sqlThe Mistake
The engineer wants to mirror /tmp/rsync-test/source/ into /tmp/rsync-test/destination/. They accidentally omit the trailing slash on the source and include --delete.
rsync -av --delete /tmp/rsync-test/source /tmp/rsync-test/destination/The output shows what happened:
sending incremental file listdeleting historical_archive/backup.tar.gzdeleting historical_archive/deleting db.sqldeleting config.ymlsource/source/config.ymlsource/db.sql
sent 218 bytes received 102 bytes 640.00 bytes/sectotal size is 36 speedup is 0.11Examine the target directory now:
$ tree /tmp/rsync-test/destination//tmp/rsync-test/destination/└── source ├── config.yml └── db.sqlThe historical_archive/ directory was deleted completely. The original config.yml and db.sql sitting at the root of destination/ were unlinked. In their place sits a new directory called source/.
Because Linux filesystems like ext4 or XFS do not put unlinked files into a trash bin, those inodes were marked as free. On an SSD with active TRIM support, that data is wiped almost immediately.
Defensive Shell Scripting Patterns for rsync
Production backup scripts should never execute raw rsync -av --delete $SRC $DST commands directly. Implement sanity checks to catch missing directories, unmounted volumes, and runaway deletion counts before files are touched.
Fail-Safe 1: Pre-Flight Mount and Directory Validation
If your source directory is an NFS share, an external hard drive, or an encrypted partition, an unexpected unmount turns your source path into an empty directory. If rsync runs against an empty directory with --delete, it unlinks your entire destination archive.
Test that the source contains expected files before calling rsync:
#!/usr/bin/env bashset -euo pipefail
SOURCE_DIR="/mnt/nfs_storage/"DEST_DIR="/mnt/local_backup/"CANARY_FILE="${SOURCE_DIR}/.mounted_canary"
# Verify source mount point using findmntif ! findmnt -M "${SOURCE_DIR}" > /dev/null 2>&1; then echo "ERROR: Source ${SOURCE_DIR} is not a mounted filesystem." >&2 exit 1fi
# Verify canary file existenceif [[ ! -f "${CANARY_FILE}" ]]; then echo "ERROR: Canary file missing from source. Partition may be unmounted or corrupted." >&2 exit 2fi
# Ensure trailing slashes are consistently appendedSOURCE_DIR="${SOURCE_DIR%/}/"DEST_DIR="${DEST_DIR%/}/"
echo "Pre-flight checks passed. Running rsync..."rsync -av --delete "${SOURCE_DIR}" "${DEST_DIR}"Fail-Safe 2: Using --max-delete as a Circuit Breaker
The --max-delete=NUM parameter halts rsync if the number of files slated for deletion exceeds the defined integer. This protects you from wiping an entire storage array due to a malformed command.
rsync -av --delete --max-delete=50 /srv/data/ /mnt/backup/data/If a user accidentally renamed a top-level directory on the source, an unconstrained rsync run would delete thousands of files on the destination and re-upload them. With --max-delete=50, rsync throws an error as soon as the 51st deletion is reached:
Number of deletions exceeded --max-delete limit of 50rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1207) [sender=3.2.7]The process aborts, keeping the remaining files intact.
Fail-Safe 3: Implementing --backup and --backup-dir
Instead of unlinking files immediately, you can instruct rsync to move any file that would be deleted or modified into a dated quarantine folder. This gives you the speed of --delete with the safety of a multi-day trash bin.
#!/usr/bin/env bashset -euo pipefail
SOURCE="/var/www/production/"DEST="/backup/www/latest/"TIMESTAMP=$(date +%Y-%m-%d_%H%M%S)RECYCLE_BIN="/backup/www/deleted_${TIMESTAMP}/"
rsync -av \ --delete \ --backup \ --backup-dir="${RECYCLE_BIN}" \ "${SOURCE}" \ "${DEST}"If a file exists on /backup/www/latest/ that is no longer on /var/www/production/:
- It is moved out of
/backup/www/latest/. - It is placed into
/backup/www/deleted_2026-11-21_090000/, preserving its relative directory structure. - The latest mirror remains a clean 1:1 replica of production.
- If an accidental deletion occurred, you can pull the file back out of the recycle folder.
You can then run a maintenance cron job that cleans out quarantine folders older than 30 days using find:
find /backup/www/ -maxdepth 1 -type d -name "deleted_*" -mtime +30 -exec rm -rf {} +Production-Grade Backup Script with Validation and Logging
Here is a complete, deployable bash backup script incorporating environment validation, itemized dry-run parsing, circuit breakers, and checksum verification.
#!/usr/bin/env bash# ==============================================================================# PURPOSE: Mirror critical directories with verification and deletion safety.# ==============================================================================
set -o errexitset -o nounsetset -o pipefail
# ConfigurationSRC_DIR="/srv/applications"DST_DIR="/mnt/backups/applications"LOG_DIR="/var/log/rsync"MAX_DELETION_LIMIT=200CHECKSUM_MODE=true
# Timestamp setupDATE_STAMP=$(date +%Y%m%d_%H%M%S)LOG_FILE="${LOG_DIR}/sync_${DATE_STAMP}.log"TRASH_DIR="${DST_DIR}_deleted/${DATE_STAMP}"
mkdir -p "${LOG_DIR}"
# Enforce explicit trailing slashes for directory contents mirroringSRC="${SRC_DIR%/}/"DST="${DST_DIR%/}/"
echo "[${DATE_STAMP}] Starting pre-sync verification..." | tee -a "${LOG_FILE}"
# 1. Verify existence of source and destination directoriesif [[ ! -d "${SRC}" ]]; then echo "CRITICAL: Source directory ${SRC} does not exist." | tee -a "${LOG_FILE}" >&2 exit 1fi
if [[ ! -d "${DST}" ]]; then echo "WARNING: Destination ${DST} does not exist. Initializing path." | tee -a "${LOG_FILE}" mkdir -p "${DST}"fi
# 2. Check for empty source directory to prevent mass wiping targetSOURCE_FILE_COUNT=$(find "${SRC}" -mindepth 1 -maxdepth 2 | wc -l)if [[ "${SOURCE_FILE_COUNT}" -eq 0 ]]; then echo "CRITICAL: Source directory is empty. Sync aborted to prevent deletion." | tee -a "${LOG_FILE}" >&2 exit 2fi
# 3. Base arguments arrayRSYNC_OPTS=( --archive --verbose --human-readable --itemize-changes --delete --delete-after --max-delete="${MAX_DELETION_LIMIT}" --backup --backup-dir="${TRASH_DIR}")
if [[ "${CHECKSUM_MODE}" == "true" ]]; then RSYNC_OPTS+=(--checksum)fi
# 4. Mandatory Dry-Run Validationecho "[${DATE_STAMP}] Executing dry-run simulation..." | tee -a "${LOG_FILE}"DRY_RUN_OUTPUT=$(rsync "${RSYNC_OPTS[@]}" --dry-run "${SRC}" "${DST}")
# Count how many deletions are plannedDELETIONS_DETECTED=$(echo "${DRY_RUN_OUTPUT}" | grep -c '^\*deleting' || true)
echo "Planned deletions: ${DELETIONS_DETECTED}" | tee -a "${LOG_FILE}"
if [[ "${DELETIONS_DETECTED}" -gt "${MAX_DELETION_LIMIT}" ]]; then echo "CRITICAL: Planned deletions (${DELETIONS_DETECTED}) exceed threshold (${MAX_DELETION_LIMIT})." | tee -a "${LOG_FILE}" >&2 echo "Aborting synchronization. Inspect output manually." | tee -a "${LOG_FILE}" >&2 exit 3fi
# 5. Live Synchronizationecho "[${DATE_STAMP}] Running production transfer..." | tee -a "${LOG_FILE}"
if rsync "${RSYNC_OPTS[@]}" "${SRC}" "${DST}" >> "${LOG_FILE}" 2>&1; then echo "[$(date +%Y%m%d_%H%M%S)] Synchronization finished successfully." | tee -a "${LOG_FILE}"else EXIT_CODE=$? echo "[$(date +%Y%m%d_%H%M%S)] Synchronization failed with exit code: ${EXIT_CODE}" | tee -a "${LOG_FILE}" >&2 exit "${EXIT_CODE}"fi
# 6. Cleanup empty trash directory if no deletions actually occurredif [[ -d "${TRASH_DIR}" ]] && [[ -z "$(ls -A "${TRASH_DIR}")" ]]; then rmdir "${TRASH_DIR}"fiMake the script executable:
chmod +x secure-sync.shTroubleshooting Common Failures and Edge Cases
When running rsync in enterprise setups, file locks, filesystem permissions, and transient input/output errors can alter deletion behaviors.
+-------------------------------------------------------------------------------+| RSYNC DELETION LOGIC GATE |+-------------------------------------------------------------------------------+| Source Scan Encountered I/O Error? || ├── YES: Refuse to execute deletions (Safety lock to prevent data wiping) || └── NO: Evaluate destination items against source. Prune unlinked files. |+-------------------------------------------------------------------------------+1. IO error encountered, skipping file deletion
During a run with --delete, you may see this output near the end of the log:
IO error encountered, skipping file deletionThis is an intentional rsync safety mechanism. If rsync encounters a read error on the source (for example, a disk read timeout, an unreadable block, or a permissions error on a subdirectory), it disables the deletion phase.
The rationale is clear: if rsync could not read a directory on the source, it cannot confirm whether the files inside it were deleted or simply unreadable. Deleting them from the target under those conditions could result in data loss.
Dangerous Workaround: Passing --ignore-errors.
Do not do this unless you understand the consequences:
# HAZARDOUS COMMAND:rsync -av --delete --ignore-errors /srv/data/ /mnt/backup/data/The --ignore-errors flag forces rsync to proceed with deletions even if read operations failed on the source. If a filesystem driver glitch causes /srv/data/users to return an I/O error, rsync ignores the error and wipes /mnt/backup/data/users entirely.
Correct Fix: Identify and resolve the source permission issue or hardware error:
# Find unreadable files on the source filesystemfind /srv/data/ ! -readable -pruneFix the ownership or read permissions:
chmod -R u+r /srv/data/2. Deletion Fails with Permission denied on Target
rsync: delete_file: unlink(var/log/auth.log) failed: Permission denied (13)This error occurs when the rsync process has write permissions on the file itself, but lacks write permissions on the parent directory containing the file.
In Linux, deleting a file requires the write (w) and execute (x) permissions on the directory containing the inode, because unlinking modifies the directory’s table of file names:
# Check parent directory permissionsls -ld /mnt/backup/data/var/log/
# Grant the synchronization user write permissions to the parent directorychown -R backupuser:backupuser /mnt/backup/data/chmod -R 775 /mnt/backup/data/3. File Disappeared During Transfer
file has vanished: "/srv/data/sessions/sess_9a8fbc"rsync warning: some files vanished before they could be transferred (code 24)This is not a deletion error. It occurs when a source file is removed by an external process (such as a web application cleaning up temporary sessions) between the time rsync builds its file list and the time it attempts to read that file.
Exit code 24 indicates that the transfer completed, but some source files disappeared during the run. In automated bash scripts using set -e, this causes the script to abort.
To handle this cleanly in automation, accept code 24 as a non-fatal warning:
rsync -av --delete /srv/data/ /mnt/backup/data/ || RSYNC_STATUS=$?
if [[ ${RSYNC_STATUS:-0} -eq 0 ]] || [[ ${RSYNC_STATUS} -eq 24 ]]; then echo "Sync succeeded (with or without vanished files)."else echo "Sync failed with error code ${RSYNC_STATUS}." >&2 exit "${RSYNC_STATUS}"fi4. Symlinks Deleted Unexpectedly
When syncing directory structures containing symbolic links, passing incorrect symlink flags will trigger deletions.
If the source contains:
/srv/data/shared_link -> /opt/shared/If you run:
rsync -av --delete /srv/data/ /mnt/backup/data/Archive mode (-a) includes -l, which copies symlinks as symlinks. The destination receives the exact symlink.
However, if an engineer adds the -L (or --copy-links) flag:
rsync -avL --delete /srv/data/ /mnt/backup/data/rsync transforms the symlink into a real directory containing the files from /opt/shared/. On the next run, if another script omits -L and reverts to standard -a, rsync sees a directory on the target where a symlink should be, unlinks the entire directory and its contents, and replaces it with the symlink.
Rule: Standardize on symlink handling across all sync scripts. Never mix -l and -L across runs against the same destination.
Cross-Platform and Filesystem Nuances
Different filesystems handle filenames, metadata, and timestamps differently. Running rsync across mixed environments can trigger false changes and unexpected deletions.
1. Case Sensitivity (macOS APFS vs Linux ext4)
macOS APFS and HFS+ are case-insensitive by default (preserving case, but treating File.txt and file.txt as identical). Linux filesystems (ext4, XFS, Btrfs) are case-sensitive.
If you sync from Linux to a macOS target:
- Source has
document.pdfandDocument.pdf. - macOS filesystem maps both to the same file.
- During the deletion phase, rsync may delete one or both files because the directory listing on the target cannot reconcile the two distinct inodes.
2. FAT32 / exFAT 2-Second Timestamp Window
FAT32 and exFAT store timestamps with a 2-second resolution. Modern Linux filesystems store timestamps down to the nanosecond.
When synchronizing from ext4 to an external USB drive formatted with exFAT, rsync will detect a timestamp discrepancy of up to 2 seconds on every file on every run. If you use --delete, it will not delete identical files, but it will continuously rewrite them.
To normalize timestamp comparisons across FAT/exFAT filesystems, use --modify-window:
rsync -av --modify-window=2 --delete /home/user/documents/ /media/usb/documents/This tells rsync to treat timestamps within 2 seconds of each other as identical, skipping unnecessary writes.
Auditing and Parsing rsync Logs
To maintain accountability across automated sync jobs, output structured transfer logs to disk using --log-file and --log-file-format.
Configuring the Output Format
rsync -av --delete \ --log-file=/var/log/rsync/audit.log \ --log-file-format="%t [%p] %o %f (%l bytes)" \ /srv/storage/ /mnt/target/Parameters used in the log format string:
%t: Current timestamp.%p: Process ID.%o: Operation type (e.g.,send,recv,del.).%f: Clean filename path.%l: File length in bytes.
Sample log lines written to /var/log/rsync/audit.log:
2026/11/21 09:15:02 [14201] recv config/app.json (1024 bytes)2026/11/21 09:15:03 [14201] del. old_config/settings.ini (412 bytes)2026/11/21 09:15:04 [14201] del. cache/session_88192.tmp (8192 bytes)Parsing Deleted Files with awk
To generate a post-sync report listing only the files deleted during the transfer:
awk '$3 == "del." {print $4}' /var/log/rsync/audit.logTo extract the total volume of deleted data in bytes:
awk '$3 == "del." {gsub(/[()bytes]/, "", $5); sum += $5} END {print "Total bytes reclaimed: " sum}' /var/log/rsync/audit.logOperational Runbook: Executing a Sync Safely
Before running any command that synchronizes directories with deletion enabled, walk through this checklist:
+--------------------------------------------------------------------------+| SAFE RSYNC EXECUTION SEQUENCE |+--------------------------------------------------------------------------+| 1. Confirm Trailing Slashes || - Source has trailing slash: /path/to/source/ || - Target has trailing slash: /path/to/target/ || || 2. Run Itemized Dry-Run Simulation || rsync -avhn --delete -i /path/to/source/ /path/to/target/ || || 3. Audit Planned Deletions || Filter output: ... | grep '^\*deleting' || Ensure no critical parent directories are marked for unlinking. || || 4. Run With Deletion Circuit Breakers || Add --max-delete=50 and --backup-dir=/path/to/trash/ || || 5. Periodic Data Integrity Audit || Run with -c (--checksum) to verify data content over metadata. |+--------------------------------------------------------------------------+- Verify Paths: Check both source and destination paths manually. Make sure the trailing slashes are present on both paths if you intend to mirror contents.
- Execute Simulation: Run the command with
-n,-v, and-i. - Inspect the Output: Verify that lines tagged with
*deletingmatch files you intentionally removed from the source. - Use Staging or Backups: Use
--backupand--backup-dirin production automation scripts to stage unlinked files rather than permanently destroying them. - Enforce Checksums Periodically: Run with
-con a weekly or monthly schedule to catch silent data corruption, bit rot, and timestamp drift.