Commands.page Logo

How to Copy Only Newer Files in Ubuntu Linux

This article demonstrates the most effective methods for copying only newer files from a source to a destination directory in Ubuntu. By utilizing specific command-line flags, you can synchronize folders while preserving existing files that are more recent than the source, saving time and preventing data loss during manual backups.

Using the CP Command

The simplest way to copy only newer files is using the cp command with the -u flag. This flag stands for “update” and ensures that a file is only copied if it does not exist in the destination or if the source file is newer than the destination file.

Open your terminal and use the following syntax:

cp -u /path/to/source/* /path/to/destination/

For recursive copying including subdirectories, add the -R flag:

cp -Ru /path/to/source/ /path/to/destination/

Using the Rsync Command

For more robust synchronization, rsync is the preferred tool. It provides greater control and efficiency when dealing with large directories. The -u flag works similarly here, skipping files that are newer on the receiving side.

Use the following command to sync only newer files:

rsync -au /path/to/source/ /path/to/destination/

In this command, -a enables archive mode to preserve permissions and timestamps, while -u ensures only newer files are transferred. This method is generally faster than cp for large datasets because it checks file sizes and timestamps before transferring data.

Verifying the Results

After running either command, you can verify that only the intended files were copied by checking the timestamps in the destination folder. Use the ls -l command to view the modification times and ensure that existing newer files in the destination remain unchanged.

ls -l /path/to/destination/

These tools allow you to maintain up-to-date backups without overwriting recent work stored in your destination directory.