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

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

cp

Copy files and whole directory trees, preserving attributes when needed.

rsync

Sync directories locally or over SSH, transferring only what changed.

ls

List the contents of a directory, with options for hidden files, long format, sorting and more.

Concepts involved: File permissions

More how-to guides

Check disk space in Linux

See how much space is left, and find out what is using it.

Extract a .tar.gz archive

Unpack tar.gz, tar.bz2, tar.xz and zip archives from the command line.

Free a port that is already in use

Find which process holds a port and stop it cleanly.

Find and replace text in files

Replace text in one file or across a whole project, safely.