How to Copy a Directory in Linux
Copy a directory and its contents with cp, including hidden files and nested folders.
Copying a directory is different from copying a single file because the command must walk the directory tree. `cp -r` is the basic solution; `cp -a` is often better for backups and migrations.
Step by step
1 Copy a directory recursively
$ cp -r app/ app-backup/ Copies the directory and its contents into the destination.
2 Preserve metadata
$ cp -a app/ app-backup/ Archive mode preserves permissions, timestamps, symbolic links and other metadata where possible.
3 Copy into an existing directory
$ cp -r app/ backups/ The resulting path is normally `backups/app/` when backups already exists.
4 Watch what is copied
$ cp -av app/ backups/ Verbose mode prints the files as they are copied.
Tips worth knowing
- Check the destination before using recursive copy on large trees.
- Use `rsync -a` for repeatable large directory transfers.
- Do not assume cp creates a missing parent path unless the destination itself is valid.
Frequently asked questions
How do I copy a folder in Linux?
Use `cp -r source/ destination/`.
What is cp -a?
Archive mode is intended to preserve filesystem metadata and symbolic links while copying recursively.
Should I use cp or rsync?
cp is simple for local one-off copies; rsync is better for repeatable or large directory synchronisation.
The commands behind it
Copy files and whole directory trees, preserving attributes when needed.
rsyncSync directories locally or over SSH, transferring only what changed.
lsList the contents of a directory, with options for hidden files, long format, sorting and more.
Concepts involved: File permissions
More how-to guides
See how much space is left, and find out what is using it.
Extract a .tar.gz archiveUnpack tar.gz, tar.bz2, tar.xz and zip archives from the command line.
Free a port that is already in useFind which process holds a port and stop it cleanly.
Find and replace text in filesReplace text in one file or across a whole project, safely.