The cp command enables you to copy and then paste a file or directory. The initial object is left where it is, but an exact duplicate of that object is created at the destination you specify. When you copy directories, you must specify the -R option to copy the specified directory recursively.
Syntax
The syntax of the cp command is:
$ cp [options] {file/directory name to copy} {file/directory name destination}
For example, to copy the ~/myfiles directory and its contents to /opt/myfiles:
$ cp -R ~/myfiles /opt/myfiles
If you encounter below error while running the cp command:
cp: command not found
you may try installing the below package as per your choice of distribution:
Distribution | Command |
---|---|
OS X | brew install coreutils |
Debian | apt-get install coreutils |
Ubuntu | apt-get install coreutils |
Alpine | apk add coreutils |
Arch Linux | pacman -S coreutils |
Kali Linux | apt-get install coreutils |
CentOS | yum install coreutils |
Fedora | dnf install coreutils |
Raspbian | apt-get install coreutils |
cp Command Examples
1. Copy a file to another location:
$ cp path/to/source_file.ext path/to/target_file.ext
2. Copy a file into another directory, keeping the filename:
$ cp path/to/source_file.ext path/to/target_parent_directory
3. Recursively copy a directory’s contents to another location (if the destination exists, the directory is copied inside it):
$ cp -R path/to/source_directory path/to/target_directory
4. Copy a directory recursively, in verbose mode (shows files as they are copied):
$ cp -vR path/to/source_directory path/to/target_directory
5. Copy text files to another location, in interactive mode (prompts user before overwriting):
$ cp -i *.txt path/to/target_directory
6. Follow symbolic links before copying:
$ cp -L link path/to/target_directory
Conclusion
cp is the copy command included in the GNU coreutils package, which is installed by default on nearly every Linux distribution. cp is for simple copying. It may be all you need to maintain regular backups.