← All commands
THE COMMAND REFERENCE

cp

Copy files and directories.

Last updated

GNU

Implementation-level reference; examples are not certified for every installed version.

Overview

cp copies files. With two names it copies the first to the second; with more, the last must be an existing directory that receives the copies. It overwrites an existing target file without asking.

Background

A cp command appeared in Version 1 Unix, according to the FreeBSD and macOS manuals. Today the name covers GNU cp, the cp that macOS ships, and the cp applet in BusyBox. They agree on -R and -p, and differ on archive mode -a, no-clobber -n, and update -u.

Examples

Copy a file to a new name and show the copy:

cp notes.txt copy.txt && cat copy.txt

Copy a file into an existing directory, keeping its name:

cp app.log logs/ && ls logs

Copy several files into a directory; the last name is the destination:

cp notes.txt app.log logs && ls logs

Copy a directory and everything inside it. -R is the portable spelling of recursive copy:

cp -R logs logs-copy && ls logs-copy

Keep the modification time and permissions of the original:

cp -p notes.txt kept.txt && ls kept.txt

Options

-R
Copy directories recursively. -r is accepted by all three implementations too, but -R is the one
POSIX defines.

-p
Preserve the modification time, access time and permission bits where possible.

Common mistakes

cp dir other fails without -R, and cp -R logs logs-copy creates logs-copy/server.log the first time but logs-copy/logs/server.log if logs-copy already exists. A trailing slash on a source directory means different things on GNU and BSD, so avoid it when copying directories. cp silently overwrites; -i asks first on a terminal.

Portability

Only -R and -p are in the Common examples. Archive mode -a, no-clobber -n and update -u differ in meaning or availability between GNU, BSD and BusyBox. The Common examples were executed on GNU coreutils 9.11, macOS system tools, and BusyBox 1.37.0 (see the development guide for the exact check).

About GNU cp

GNU cp is part of GNU coreutils, and this page's checks ran coreutils 9.11. It adds -t to name the destination directory first.

GNU examples

Name the destination directory first with -t, which suits xargs pipelines. This option is a GNU extension:

cp -t logs notes.txt app.log && ls logs

References

Original explanations, with upstream documentation for further reading. FreeBSD references are comparison material, not a claim of Apple version equivalence.