rsync --delete Explained and Practical Directory Cleanup

Learn what rsync --delete does, common usage patterns, and key precautions, including a practical way to quickly clean a target directory using an empty source directory.

The core purpose of rsync --delete is to remove files in the target directory that do not exist in the source directory, so both sides stay consistent.

Typical use cases include:

  • Cleaning stale files on the target side during sync
  • Quickly emptying a target directory by syncing from an empty source directory

Basic Syntax

1
rsync -a --delete source_dir/ target_dir/
  • -a: archive mode, preserves permissions, timestamps, and other attributes
  • --delete: removes extra files on the target side

Important note: whether source_dir ends with / changes behavior. With /, rsync syncs directory contents; without /, it syncs the directory itself.

Quickly Empty a Target Directory with an Empty Source

If your goal is to keep the directory path but clear all contents, use an empty directory as the source:

1
2
3
4
5
# 1) Create an empty directory
mkdir -p /tmp/empty_dir

# 2) Sync and delete target-side content
rsync -a --delete /tmp/empty_dir/ /path/to/target_dir/

In large-directory scenarios, this is often more efficient than deleting files one by one, and it is easier to automate in scripts.

Common Extended Options

  • --delete-before: delete before transfer, which can be faster in some cases
  • --progress: show transfer and processing progress

Example (cleaning an Nginx log directory):

1
rsync -a --delete --progress /tmp/empty_dir/ /var/log/nginx/

Recommendations

  • Run with --dry-run first to verify the deletion scope
  • Back up the target directory before running in production
  • For critical paths, schedule execution during off-peak hours
记录并分享
Built with Hugo
Theme Stack designed by Jimmy