How To Copy Directory Linux [4 Best Methods]

Written by

Reviewed by

Last updated: June 25, 2024

Expert verified

SVG Image

TL;DR

To copy directory Linux using the cp command, follow these methods:

  1. Basic Copying: Use cp -r /source_directory /destination_directory to copy directories recursively.
  2. Preserve Attributes: Include -p to maintain timestamps and permissions: cp -rp /source_directory /destination_directory.
  3. Interactive Prompt: Add -i to get a confirmation before overwriting: cp -ri /source_directory /destination_directory.
  4. Verbose Output: Use -v to see detailed progress of the copy: cp -rv /source_directory /destination_directory.
  5. Avoid Overwriting: Add -n to ensure existing files are not overwritten: cp -rn /source_directory /destination_directory.
  6. Update Only Changed Files: Use -u to copy only newer or non-existent files: cp -ru /source_directory /destination_directory.
  7. Exclude Specific Files: Use rsync --exclude to skip certain files or directories: rsync -av --exclude 'pattern' /source_directory/ /destination_directory/.

    Copying directories in Linux can seem tricky, but it’s a task you’ll often need to handle. Whether you’re backing up data, moving to a new system, or organizing files, knowing the right commands and methods makes it much easier. In this post, I’ll guide you through using the cp command to copy directories, along with other powerful tools like rsync and tar. You’ll also learn best practices to avoid data loss and ensure your copies are accurate. By the end, you’ll feel confident managing your directories in Linux.

    Common cp Command Options and Examples

    Option Command ExampleExplanation
    -r (recursive)cp -r /source_directory /destination_directoryCopies the entire directory structure from source to destination.
    -i (interactive)cp -ri /source_directory /destination_directoryAsks for confirmation before overwriting files in the destination.
    -p (preserve)cp -rp /source_directory /destination_directoryKeeps original file attributes intact during the copy.
    -v (verbose)cp -rv /source_directory /destination_directoryShows each file and directory as it is copied, useful for monitoring progress.
    -n (no-clobber)cp -rn /source_directory /destination_directoryEnsures existing files in the destination are not replaced.
    -u (update)cp -ru /source_directory /destination_directoryUpdates only those files that have changed or are new.
    --backupcp --backup /source_directory/file /destination_directory/Makes a backup of the destination file before overwriting it.
    --parentscp --parents /source_directory/file /destination_directory/Preserves the directory structure in the destination.
    -a (archive)cp -a /source_directory /destination_directoryEquivalent to -rp and is commonly used for backups.
    --exclude (rsync only)rsync -av --exclude 'pattern' /source_directory /destination_directoryExcludes specified files or directories from being copied.

    How To Copy Directory Linux Using cp Command?

    To copy directory Linux using the cp command, use the -r option to copy recursively. This command copies the entire directory structure, including all files and subdirectories. For example, run cp -r /source_directory /destination_directory to copy everything from /source_directory to /destination_directory.

    To preserve file attributes like timestamps and permissions, add the -p option: cp -rp /source_directory /destination_directory. Use the -i option for an interactive prompt before overwriting files: cp -ri /source_directory /destination_directory. This ensures you copy directories safely and effectively.

    That was the quick answer, for a more detailed one, here are 7 ways to Linux copy directory.

    1. Basic Copying of a Directory

    To copy a directory, including all its files and subdirectories, you need to use the -r (recursive) option. Follow these steps to Linux cp directory:

    1. Access your Linux terminal by using a shortcut, Ctrl+Alt+T.
    open terminal
    1. To copy folder Linux, including all its contents, enter the following command:
    cp -r source_directory_path destination_directory_path

    This command recursively copies the directory and all its contents to a new location. -r tells cp to copy directories recursively.

    copying directory to another directory

    2. Preserving File Attributes

    If you also want to preserve the attributes (such as permissions, timestamps, and ownership), add the -p flag:

      cp -rp source_directory_path destination_directory_path

      This command ensures that the copied directory retains its original attributes.

      copying directory with its attributes
      1. Ensure the directory has been copied as expected by listing the contents of the destination directory:
      ls destination_directory_path

      The output will be:

      verifying in the destination directory

      3. Copying Multiple Directories

      You can copy multiple directories at once by specifying them in the command.

      cp -r directory1 directory2 directory3 destination_directory/

      This will copy directory1 directory2 directory3 into destination_directory. Replace the directory with the names of your desired directories.

      copying multiple directories at a time

      4. Verbose Output

      For detailed output showing the progress of the copy operation, use the -v (verbose) option.

      sudo cp -rv /path_to_source_directory /destination_directory
      • -v: Show verbose output.

      This option is useful for tracking the files as they are being copied.

      tracking files as they are being copied

      5. Excluding Specific Files or Directories

      To exclude certain files or directories while copying, use the –exclude option.

      rsync -av --exclude 'pattern' source_directory/ destination_directory/

      Replace pattern with the actual pattern that you want to exclude.

      • –exclude ‘pattern’: Exclude files or directories matching the pattern.

      Note: rsync is used here because cp does not have an exclude option. However, this method achieves the desired result.

      excluding specific files during copying

      6. Overwriting Existing Files

      By default, cp will overwrite existing files in the destination. If you want to avoid this, use the -n (no-clobber) option.

      cp -rn source_directory destination_directory
      • -n: Do not overwrite existing files.

      This is useful when you want to ensure that existing files in the destination are not replaced.

      copying files while avoiding overwriting

      7. Updating Only Changed Files

      To copy only the files that have changed or are new, use the -u (update) option.

      cp -ru source_directory destination_directory
      • -u: Copy only when the source file is newer than the destination file or when the destination file is missing.

      This option is efficient for incremental updates.

      copying only changed or updated files

      How to Copy Directory in Linux Using Other Methods

      While the cp command is a powerful and widely-used tool for copying directories in Linux, there are several other methods that can be more efficient or provide additional features. These methods include using rsync, tar, and graphical user interface (GUI) tools. Each of these methods offers unique advantages, whether it’s for syncing large directories, preserving file attributes, or providing a more user-friendly experience.

      Below, I’ll explore these methods in detail.

      1. rsync Command

      rsync is a utility for efficiently transferring and synchronizing files across computer systems, using a delta transfer algorithm. It’s particularly useful for copying large directories or for incremental backups. Here is the step-by-step guide:

      1. Access your Terminal window and copy a directory to another location, by running the command:
      rsync -av source_directory_path/ destination_directory_path/

      -a enables archive mode to preserve permissions, timestamps, and other attributes.

      -v increases verbosity to show the files being copied.

      transfering contents of a directory to another
      1. Check the destination directory to ensure the copy operation was successful:
      ls destination_directory_path

      The output will look like this:

      verifying the transfer of contents

      2. tar Command

      The tar command is traditionally used for creating archives. Interestingly, it can also be used to copy directories by archiving a directory then immediately extracting it to a new location, making it a handy tool for preserving file permissions and attributes. Here is how to do it:

      1. Open the Terminal.
      2. Execute the following command:
      tar -cvf - source_directory_path | tar -xvf - -C destination_directory_path

      The first tar -cvf – source_directory_path creates an archive and outputs it to stdout.

      The second part, tar -xvf – -C destination_directory_path, reads from stdin to extract the archive to the destination directory.

      copying directory content by creating an archive
      1. Use the ls command to check the contents of the destination directory.
      verifying the transfer of contents using ls command

      3. Using GUI Tools to Copy Directories

      Graphical File Managers in Linux, provide a user-friendly way to manage files and directories, including copying them through a graphical interface. Follow these steps:

      1. Locate the directory you wish to copy.
      2. Right-click the directory and select Copy or use the keyboard shortcut, usually Ctrl+C.
      copying directory using GUI
      1. Open the location where you want to copy the directory.
      2. Right-click in the destination location and select Paste or use the keyboard shortcut, usually Ctrl+V.
      transfering directory to another directory using GUI
      1. The directory should now appear in the destination location.

      Best Practices for Copying Directories

      When working with Linux, copying directories is a common task that requires careful attention to detail to avoid data loss and ensure data integrity. Following best practices helps you perform these operations safely and effectively.

      🛡️ Tips to Avoid Data Loss

      Double-check source and destination paths before copying to prevent mistakes. Use the -i (interactive) option with the cp command to prompt before overwriting files (cp -ri /source_directory /destination_directory). Avoid using root privileges unless necessary, and test the command with a small set of files before copying large amounts of data.

      • Backing Up a Directory: Use rsync to back up a directory while preserving file attributes (rsync -av /source_directory /backup_directory).

      🔄 Importance of Regular Backups

      Regular backups protect your data from accidental deletion, hardware failures, and other issues. Schedule daily, weekly, or monthly backups based on how often your data changes. Use tools like rsync or set up cron jobs to automate backups.

      • Automating Backups with cron: Schedule backups with a cron job to run daily at 2 AM (0 2 * * * rsync -av /source_directory /backup_directory). Add this line to your crontab with crontab -e.

      🔍 Using Checksums to Verify Data Integrity

      Checksums are unique strings that verify file integrity. Use tools like md5sum and sha256sum to generate and check these strings. For example, generate a checksum with md5sum /source_directory/file > file.md5 and verify it with md5sum -c file.md5 to ensure files haven’t changed during copying.

      • Verifying Data Integrity After Copy: Generate checksums for the source directory with find /source_directory -type f -exec md5sum {} \; > checksums.md5, then verify in the destination directory with md5sum -c checksums.md5.

      Linux Copy Folder: In a Nutshell

      In this article, I’ve explored different methods for copying a directory in Linux, focusing on the cp command and alternatives like rsync, tar, and GUI tools.

      To learn more, I recommend:

      Frequently Asked Questions

      Can I copy directories between different Linux distributions using these methods?

      Absolutely. The methods described, such as using cp, rsync, and tar, rely on universal commands available in virtually all Linux distributions, making it feasible to copy directories across any Linux environment without compatibility issues.

      How can I copy a directory excluding certain files or subdirectories?

      To exclude specific files or subdirectories when copying a directory, utilize the rsync command coupled with the –exclude option. This allows for selective copying, providing flexibility and control over exactly what gets duplicated in the process.

      Is there a way to speed up the copying of very large directories?

      Indeed, to enhance the speed of copying large directories, especially over networks, consider employing rsync with the –compress option. For local copies, tweaking cp with ionice can optimize system resource usage, significantly speeding up the copying process.

      How do I handle copying directories with read-only files?

      When dealing with read-only files within directories you wish to copy, altering file permissions temporarily using chmod or executing the copy command with sudo can dodge permission restrictions, allowing the copy operation to proceed smoothly.

      Ojash

      Author

      Ojash is a skilled Linux expert and tech writer with over a decade of experience. He has extensive knowledge of Linux's file system, command-line interface, and software installations. Ojash is also an expert in shell scripting and automation, with experience in Bash, Python, and Perl. He has published numerous articles on Linux in various online publications, making him a valuable resource for both seasoned Linux users and beginners. Ojash is also an active member of the Linux community and participates in Linux forums.

      Akshat

      Reviewer

      Akshat is a software engineer, product designer and the co-founder of Scrutify. He's an experienced Linux professional and the senior editor of this blog. He is also an open-source contributor to many projects on Github and has written several technical guides on Linux. Apart from that, he’s also actively sharing his ideas and tutorials on Medium and Attirer. As the editor of this blog, Akshat brings his wealth of knowledge and experience to provide readers with valuable insights and advice on a wide range of Linux-related topics.

      Share this article
      Shareable URL
      Prev Post

      How to Install ADB on Linux [2 Best Methods]

      Next Post

      9 Best Methods to Bash Split String

      Leave a Reply

      Your email address will not be published. Required fields are marked *

      Read next