cp (copy)
It copies:
- files
- directories
- symbolic links
- special files (optionally)
The copied object becomes independent from the original unless linking options are used.
SECTION 1 - Copying Files
Copy one file:
cp file1.txt file2.txt
This creates file2.txt copy, with the same contents as file1.txt. If file2.txt exists, it is overwritten.
Multiple files:
cp file1 file2 file3 directory/
Copies all files into directory/
-t
Target Directory Syntax:
cp -t directory file1 file2
Equivalent to:
cp file1 file2 directory/
Useful in scripts.
SECTION 2 - Copying Directories
-r, -R, --recursive
Needed to copy directories recursively.
cp -R dir1/ dir2/
-r and -R GNU systems treat them similarly.
-Rstandard recursive-rolder, less portable
SECTION 3 - Archive Mode
-a, --archive
Preserve as much as possible of the structure and attributes of the original files in the copy (but do not attempt to preserve internal directory structure)
Equivalent to -dR --preserve=all with the reduced diagnostics.
cp -a source dest
It preserves:
- permissions
- ownership
- timestamps
- symlinks
- hard links
- xattrs
- SELinux context
SECTION 4 - Symbolic Links
SECTION 5 - Hard Links and Symbolic Links
SECTION 6 - Overwriting Behavior
-i, --interactive
Ask before overwrite.
cp -i file.txt backup/
Prompt:
overwrite 'backup/file.txt'?
-n, --no-clobber
Never overwrite.
cp -n file.txt backup/
Silently skips existing files.
-f, --force
Force overwrite.
cp -f file.txt backup/
Removes destination if necessary.
--remove-destination
Remove destination before writing.
Different from -f.
Useful for replacing special files/symlinks safely.
SECTION 7 - Preserving Attributes
-p
Preserve metadata.
cp -p file backup
--preserve=...
Fine-grained control.
cp --preserve=mode,ownership,timestamps file backup
Preserve Options:
| Attribute | Meaning |
|---|---|
mode |
permissions |
ownership |
owner/group |
timestamps |
atime/mtime |
links |
hard links |
context |
SELinux |
xattr |
extended attributes |
all |
preserve everything |
--no-preserve
Disable preservation selectively.
cp -a --no-preserve=ownership src dst
SECTION 8 - Sparse Files
SECTION 9 - Reflinks (Copy-on-Write)
SECTION 10 - Recursive Filesystem Behavior
SECTION 11 - --parents
SECTION 12 - Verbose and Debugging
-v
Show copied files. Output:
'file' -> 'backup/file'
--debug
Explain copy operations in detail.
Implies -v.
SECTION 13 - Backup Options
-b
Create backups before overwrite.
-S
Custom backup suffix.
cp -b -S .bak file backup/
Creates:
file.bak