Skip to content
shellhacks.dev
Command Line

How to Use cp to Copy Files and Directories Safely

Copy files and directories with cp without overwriting by accident. Learn recursive copies, archive mode, the trailing slash rule and how to keep a backup.

6 min read
Summarize in AI
Illustration for "How to Use cp to Copy Files and Directories Safely": a terminal session, a directory tree, an archive box.

Copying a file is easy. Copying a directory has an edge that has cost people their data: cp -r src dest does one thing when dest exists and another when it does not. This post shows the options worth knowing and that edge, alongside the other file tools in the grep, sed and awk guide. The related move command is in how to use mv.

The options below are from GNU coreutils 9.4 on Debian 13. BSD and macOS cp support -r, -a, -i, -n and -v.

The basic forms

Shell
cp report.txt report-backup.txt
cp report.txt ~/Documents/
cp a.txt b.txt c.txt backup/
cp -r project project-copy

With more than two arguments, the last must be an existing directory. Without -r, copying a directory fails with cp: -r not specified; omitting directory 'project'.

Protect what you overwrite

OptionEffect
-iAsk before overwriting
-nNever overwrite an existing file
-uCopy only if the source is newer or the target is missing
--backup=numberedKeep the replaced file as name.~1~
-vPrint each copy as it happens

A common alias is alias cp='cp -i'. We do not recommend it, because it teaches your fingers that nothing is lost and then fails you on a machine without the alias. Use -i in the habit instead, or -n in scripts.

The trailing slash edge

Shell
mkdir dest
cp -r src dest
ls dest

Because dest exists, the copy lands inside it, as dest/src. Run the same command when dest does not exist and you get a copy named dest. A script that runs twice therefore makes dest/src on the second run. To copy the contents of src into dest every time, use a dot:

Shell
mkdir -p dest
cp -r src/. dest

With GNU cp, -T asks the same question differently: cp -rT src dest always treats dest as the target itself, never a folder to copy into.

Copy with its metadata

Shell
cp -a /srv/site /backup/site

-a equals -dR --preserve=all: recursive, links preserved as links, and mode, ownership, timestamps, context and extended attributes kept. Without it, copied files get the current time and your umask, and a copied symbolic link may become a copy of its target. Ownership is preserved only if you are root. For large trees or remote copies, rsync -a is better: it can resume and skip unchanged files.

Copy many files at once

Shell
find . -name '*.log' -print0 | xargs -0 cp -t /archive

GNU's -t DIR names the destination first, so the file list can come last, which is what xargs produces. On macOS use find ... -exec cp {} /archive \; or install GNU coreutils.

Sparse files and cloning

cp --reflink=auto makes an instant copy-on-write clone on file systems that support it, such as Btrfs and XFS with reflink, and falls back to a normal copy elsewhere. Sparse files are kept sparse by default in GNU cp (--sparse=auto), which matters for VM disk images.

What cp does with your data

cp opens the source for reading, creates or truncates the destination for writing, and copies the bytes. Everything else, permissions, owner, timestamps and extended attributes, is separate work that it only does when asked. A plain copy gives the new file the current time and the invoking user, with a mode taken from the source and filtered by umask. The difference is easy to see, and it matters for anything that depends on timestamps, such as make or rsync.

Shell
touch -d "2020-01-01 10:00" old
cp old new1
cp -p old new2
ls -l --time-style=long-iso old new1 new2
Text
-rw-r--r-- 1 alex alex 0 2026-11-04 13:45 new1
-rw-r--r-- 1 alex alex 0 2020-01-01 10:00 new2
-rw-r--r-- 1 alex alex 0 2020-01-01 10:00 old

The plain copy new1 got today's time, and -p kept the original. The archive option -a is -dR --preserve=all: it recurses, keeps links as links, and preserves mode, ownership, timestamps, and extended attributes where it can. Ownership is only preserved when you run as root, which is why a backup made by a normal user quietly turns every file into the user's own.

Overwrite protection that works

By default cp replaces an existing file without asking. Two options change that, and they do different things. -n never overwrites and says nothing, which makes it easy to miss that nothing happened. -i asks first, and fails in a script with no terminal because it cannot read an answer.

Shell
echo one > f1; echo two > f2
cp -n f1 f2
cat f2
cp -i f1 f2 < /dev/null
echo "status $?"
Text
two
cp: overwrite 'f2'? status 1

The first copy changed nothing and exited without a message, and f2 still holds two. The second tried to prompt, got no input and stopped with status 1. The exit status of a skipped -n copy has changed between coreutils releases, so do not build logic on it. A script that cares should test for the file first with [ -e dest ] and make the decision visible, or use cp --update=none, available in coreutils 9.3 and later, because its name says what it does.

Directories: where the copy lands

Copying a directory into an existing one puts it inside, whether or not you add a slash to the source. That trips people who expect the contents to merge.

Shell
mkdir d1 d2 && echo z > d1/z
cp -r d1 d2
cp -r d1/ d2/
find d2
Text
d2
d2/d1
d2/d1/z

Both commands produced d2/d1. Only when the destination does not exist does the copy take the source's name, so cp -r d1 new creates new as a copy. To merge the contents of d1 into d2, copy the contents: cp -r d1/. d2/ works in GNU and BSD cp. This is a place where rsync is safer, because it treats a trailing slash on the source as "the contents", with the behavior spelled out in its manual. The clash between the two conventions is the reason copy-then-check is a good habit for large trees.

A safe habit for copying

Before copying into a directory that already exists, list the destination. A one-second look prevents most overwrite accidents. Preview with cp -v on a small test, or add -n to the first run, and remove it once you trust the result. For anything that matters, copy first and verify with a checksum of both sides, for example sha256sum on the source and the copy, before you delete the original.

When cp is not enough

To copy into a folder you may not yet have, pair it with mkdir -p so the destination exists first, and to remove what a bad copy left behind, read how to use rm before you reach for a wildcard.

For anything crossing a network, use rsync or scp. For a copy that must not be partial, copy to a temporary name in the same directory, then mv it into place, because a rename is atomic and a copy is not. The complete reference is the cp invocation page, and POSIX defines the portable subset in cp.

Taggedterminal
Share

Keep reading

Get new posts by email

One email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.