Using rsync to Merge Two Source Directories

Abstract: Merge two source directories into one destination using sequential rsync commands to consolidate data without overwriting existing files.

Created: 2026-10-18 by

You can merge two source directories into a single destination using rsync by running the command twice in succession. First, sync the primary directory to the backup location, then run a second rsync command with the secondary directory pointing to the same destination. This approach ensures that files from both sources are combined without deleting existing data, provided you avoid destructive flags like --delete.

Understanding the Merge Strategy

The core challenge when merging directories is preventing the second synchronization operation from overwriting or removing files established by the first. By default, rsync is safe for this task because it only copies new or modified files and creates missing directories. However, if you inadvertently include flags such as --delete, the tool will remove files in the destination that do not exist in the current source. Therefore, the strategy relies on executing two separate commands rather than trying to pass multiple sources in a single invocation.

This method is particularly useful for creating comprehensive backups where different data sets reside in separate locations on your local machine but need to be consolidated on an external drive. It allows you to treat each source independently while maintaining a unified view of the backup target. For more context on how rsync handles repeated operations safely, you might find it helpful to read about whether is rsync idempotent.

Step-by-Step Execution Guide

To successfully merge your directories, follow these precise steps. Ensure you have write permissions for the destination directory before starting.

  1. Identify Your Directories: Determine the paths for your two source directories (e.g., /home/user/docs and /home/user/photos) and your single destination directory (e.g., /mnt/backup/merged).
  2. Run the First Sync: Execute the rsync command for the first source. Use the -a flag for archive mode, which preserves permissions, timestamps, and symlinks. Add -v for verbose output to monitor progress.
rsync -av /home/user/docs/ /mnt/backup/merged/

Note the trailing slash on the source directory. This syntax tells rsync to copy the contents of the directory rather than the directory itself, which is crucial for proper merging.

  1. Run the Second Sync: Immediately execute the same command structure for the second source directory, pointing to the identical destination.
rsync -av /home/user/photos/ /mnt/backup/merged/

Rsync will now scan the destination. If a file exists in the photos folder but not in the docs folder, it will be copied. If a file exists in both, rsync will compare them based on size and modification time (or checksums if specified) and update only what has changed.

Optimizing for Backup Efficiency

When performing merges for backup purposes, efficiency is key. You should consider adding the -u (update) flag to ensure rsync skips files that are newer on the receiving side. This prevents unnecessary transfers if you have manually edited files in the backup location, although this is rare in pure backup scenarios.

Additionally, if you are dealing with large datasets, the --progress flag can provide real-time feedback on transfer speeds and file percentages. This helps diagnose issues early if one of the sources contains corrupted files or permission errors. For deeper insights into excluding specific folders during these operations to save space, check out our guide on Can't Get Rsync to Exclude Specific Directories? Here's the Include Option to Try.

Common Pitfalls and Troubleshooting

A frequent mistake is using the --delete flag. If you run rsync --delete -av source1 dest followed by rsync --delete -av source2 dest, the second command will delete all files from source1 that are not present in source2. Always omit --delete unless you explicitly want to mirror a single source exactly.

Another issue arises with hidden files. Standard globbing patterns often exclude dotfiles. Ensure your source paths are explicit and do not rely on shell expansion that might skip hidden directories. If you encounter errors related to extended attributes, refer to resources discussing Rsync backup failing on xattr to resolve permission-related blocking.

Frequently Asked Questions

Can I merge three or more directories?

Yes, simply repeat the rsync command for each additional source directory, ensuring they all point to the same destination path. The order does not matter for the final result, but processing larger directories first may improve perceived performance.

Does rsync overwrite conflicting files?

Rsync compares files by size and modification time by default. If the destination file is newer, it remains untouched. If the source file is newer or the sizes differ, the source file overwrites the destination version.

What happens if I use a trailing slash incorrectly?

Omitting the trailing slash on the source creates a nested directory inside the destination. Including it ensures the contents are merged directly into the target folder, which is essential for a clean merge.

How do I handle permission errors during merge?

Ensure you are running the command with sufficient privileges, often using sudo if writing to protected system directories. Check the destination filesystem for write permissions using ls -ld on the target path.

Is it safe to interrupt the process?

If interrupted, the partially transferred files may be corrupted. Restarting the command will resume from the beginning of those specific files due to the archive mode, ensuring data integrity upon completion.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More