How do I use Linux to copy a directory recursively?

How do I use Linux to copy a directory recursively?

I want to copy a directory in Linux, including all its files and subdirectories, while preserving the structure. What is the correct command to achieve this?

Ah, the classic way! If you’re just looking for a simple, straightforward method to copy a directory in Linux, the cp command with the -r flag is your go-to.

Command:

cp -r source_directory destination_directory

Example:

cp -r /home/user/documents /home/user/backup

This will recursively copy all files and subdirectories from documents to backup.

:small_blue_diamond: Pro Tip: Instead of -r, you can use -a (archive mode) to preserve timestamps, symbolic links, and file permissions.

That’s a great start, but if you want something more efficient—especially for large directories—rsync is the way to go. It’s not just about copying; it optimizes the process by only transferring changes.

Command:

rsync -av source_directory destination_directory

Example:

rsync -av /home/user/documents /home/user/backup
  • -a preserves permissions, timestamps, and symbolic links.
  • -v provides a detailed output, so you know what’s being copied.

:small_blue_diamond: Bonus: Need to copy a directory over a network? Use:

rsync -avz user@remote:/source_directory /local_destination

The -z flag compresses data for faster transfers. Great for remote backups!

Good choices so far! But what if you need to copy a directory across different filesystems or want to package everything neatly? That’s where tar comes in handy.

Command:

tar cf - source_directory | tar xf - -C destination_directory

Example:

tar cf - /home/user/documents | tar xf - -C /home/user/backup

This method streams the directory into an archive and extracts it at the destination, preserving the full structure.

:small_blue_diamond: Best Use Case: Perfect for copying directories between different Linux environments while ensuring file attributes remain intact.