Copying Directories in Linux: Choose Between cp -r, cp -a, and rsync
Copying a directory in Linux is easy; copying it to the right shape is where mistakes happen. The destination may end up with an unexpected nested folder, hidden files may be skipped by a wildcard, or metadata may not be preserved the way a backup requires. Here’s how to pick the right command and check what it will do. Start with cp -r For a basic copy of a directory and its contents, use…
When it comes to copying directories in Linux, the choice of command matters. The three main options are cp -r, cp -a, and rsync, each with its own strengths and use cases. To avoid common pitfalls, follow these guidelines for successful directory copying.
For a basic copy of a directory and its contents, use cp -r. This recursive mode ensures that the entire directory tree is copied. However, be aware that the destination's current state affects the result. If the destination directory does not exist, cp will create it as a copy of the source. If it already exists as a directory, the copy will be placed inside it. To avoid this surprise, check the target directory before running the command.
If you want to copy hidden files along with the directory, include a dot at the end of the source path. For example, use cp -r build/. deploy/ to copy only the contents of build/ into deploy/, including any hidden files. Using a shell wildcard like cp -r build/ * deploy/ will exclude hidden files, as the shell expands * before cp runs.
When metadata and symbolic links are important, use cp -a. This archive mode preserves attributes such as permissions, ownership, timestamps, and extended attributes where supported. It also copies symbolic links as links, rather than following them to copy their targets. This is crucial for backups, migrations, or directories containing symbolic links where preserving the source tree's attributes is essential.
For repeat copies or large transfers, rsync is often more useful than starting over with cp. It can transfer changes since a previous run and report progress. The trailing slash on the source directory path indicates that you want to copy its contents into the destination directory, rather than including the source directory itself. If you omit the trailing slash, the source directory will be included in the destination path, which may not be the desired outcome.
Before running a command, ask yourself two questions: does the destination directory already exist, and do I need to copy the directory itself or only its contents? Answering these questions will help you choose the right command and avoid common copy surprises.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.