cp is the POSIX command for copying files from the command line. The basic invocation of the cp command is:
cp (OPTIONS) FILE TARGET
for copying a single file, or
cp (OPTIONS) FILE1 FILE2 ... TARGETDIR
for copying multiple files into a directory. If the target file or files exist, they are overwritten if write permission to the files is available.
Since cp is a separate program from the Unix command interpreter, which in turn is separate from the base operating system, multiple versions of cp exist. There are at least four implementations of the cp command in common use today. The System V cp is the original implementation and shows up quite often in proprietary Unix systems. BSD cp was written next and supports the POSIX standard and a couple basic extensions. GNU cp, the standard on GNU/Linux systems, has many extensions over the POSIX standard and BSD cp. Finally, the BusyBox toolkit for embedded *nix systems contains a basic cp implementation.
Under strict POSIX, there are five command options:
- -f: If a target file has no write permission, attempt to delete it rather than giving a permission error.
- -i: If a target file exists, ask the user before overwriting it. (Many Linux distributions make this mode the default)
- -p: Preserve the file attributes, including permissions, ownership, and timestamps, if possible. The default behavior is to use the current umask on the permissions and update the timestamps.
- -R: If a directory is listed, copy it and all of its contents. (there is also a -r option which may or may not differ subtly from -R)
- --: Marks the end of the options for when it is ambiguous (e.g. with a file named '-p')
GNU cp adds a number of additional options, the most important of which are:
- -a: Preserve as many aspects of the copied files as possible, including directories, subdirectories, and symbolic links. Equivalent to -pdR .
- -d: Instead of following symbolic links and copying the files they point to, copy the symbolic links themselves. Also, if two or more source files are hard linked together, preserve the hard link in the copy.
- -l: For non-directories, make hard links rather than copying.
- -u: Only overwrite a file if it has an earlier timestamp than the file being copied.
- -v: Print the name of each file as it is copied.
BSD cp adds the -v option as well as an option, -n, which unconditionally prevents it from overwriting existing files
The cp command is part of the basic toolkit of Unix commands learned quickly by any newcommer to the Unix CLI. As such, it exists on any Unix or Unix-like system, in one form or another. The most advanced variant, GNU cp, is available in GNU fileutils or GNU coreutils from http://www.gnu.org/, although you probably either have a cp, or would be unable to use it.
(CC)
This writeup is copyright 2004 D.G. Roberge and is released under the Creative Commons Attribution-NonCommercial-ShareAlike licence. Details can be found at http://creativecommons.org/licenses/by-nc-sa/2.0/ .