cp – copy files and directories

cp command
cp command

cp copies files and directories. It’s essential for duplicating, backing up, and organizing files.

Synopsis

cp [OPTIONS] SOURCE DEST
cp [OPTIONS] SOURCE... DIRECTORY

Common Options

OptionDescription
-r, -RCopy directories recursively
-iPrompt before overwriting
-nDon’t overwrite existing files
-uCopy only when source is newer
-vVerbose, show files being copied
-pPreserve permissions, timestamps, ownership
-aArchive mode (same as -rpP)
-lCreate hard links instead of copying
-sCreate symbolic links instead of copying

Examples

Copy a file

$ cp file.txt backup.txt

Copy to a directory

$ cp file.txt /tmp/
$ cp file.txt /tmp/newname.txt

Copy multiple files to directory

$ cp file1.txt file2.txt file3.txt /backup/

Copy using wildcards

$ cp *.txt /backup/
$ cp report.* /archive/

Copy directory recursively

$ cp -r project/ project_backup/

Interactive mode (ask before overwriting)

$ cp -i source.txt dest.txt
cp: overwrite 'dest.txt'? y

Don’t overwrite existing files

$ cp -n newfile.txt existing.txt
# No error, existing.txt unchanged

Preserve file attributes

$ cp -p important.txt backup.txt
# Keeps original permissions, timestamps, owner

Archive mode (for backups)

$ cp -a /var/www/ /backup/www/
# Preserves everything: permissions, symlinks, timestamps

Copy only newer files

$ cp -u *.txt /backup/
# Only copies if source is newer than destination

Verbose output

$ cp -rv src/ dest/
'src/file1.txt' -> 'dest/file1.txt'
'src/file2.txt' -> 'dest/file2.txt'
'src/subdir/file3.txt' -> 'dest/subdir/file3.txt'

Create backup of existing files

$ cp --backup=numbered file.txt /dest/
# Creates file.txt.~1~ if file.txt exists

Common Patterns

Backup with date stamp

$ cp config.yml config.yml.$(date +%Y%m%d)

Copy to multiple destinations

$ echo /dest1 /dest2 | xargs -n 1 cp file.txt

Copy preserving directory structure

$ cp --parents src/sub/file.txt /backup/
# Creates /backup/src/sub/file.txt

Tips

  • Use -i in interactive sessions to avoid accidental overwrites
  • Use -a for backups to preserve all attributes
  • For large copies, use rsync — it’s more efficient and resumable
  • Check disk space first: df -h /dest before large copies
  • Copy across machines: Use scp or rsync instead

See Also

  • mv — Move or rename files
  • rm — Remove files
  • rsync — Advanced copy with sync capabilities
  • scp — Secure copy over SSH

Tutorials