cp copies files. The original stays where it is and a second, independent file is created. The basic form is cp SOURCE DESTINATION.
Copying a file
$ cp report.txt report-backup.txt
$ ls
report-backup.txt report.txtSuccess prints nothing. If the destination is an existing directory, the copy goes inside it with the same name:
$ cp report.txt archive/
$ ls archive
report.txtYou can copy several files at once when the last argument is a directory:
$ cp a.txt b.txt archive/Wildcards work too: cp *.txt archive/ copies every visible name ending in .txt.
Overwriting
By default, cp replaces an existing destination file without asking. Two options protect you:
-iasks before overwriting.-ndoes not overwrite at all.
$ cp -i report.txt report-backup.txt
cp: overwrite 'report-backup.txt'? nSome distributions alias cp to cp -i, especially for root, so behaviour can differ between machines. The exact handling of -n messages also varies between versions.
Copying directories
A plain cp skips directories:
$ cp photos backup
cp: -r not specified; omitting directory 'photos'Use -r (or -R) to copy a directory and everything in it:
$ cp -r photos backupIf backup does not exist, it becomes a copy of photos. If backup already exists, you get backup/photos. Running the same command twice therefore gives different layouts.
Keeping details
A new copy normally gets a new modification time. -p preserves mode, ownership (when you have the rights) and timestamps. -a (archive) copies recursively and preserves as much as possible, including symbolic links as links, which makes it a good choice for backups. -v prints each file as it is copied.
Practise in the files and links lab.
Try it
- Create a file and copy it to a new name.
- Copy it again with
-iand answern. - Make a directory and copy the file into it.
- Copy that directory with
cp -rtwice and inspect the result withls -R.
Check your understanding
cp (Copy)
All 5 sections ยท no timer
Unlimited retries
Questions from every section are combined into one assessment. Answer them all correctly to complete the article.
Your completion saves in this browser. Sign in to sync it to your account.