Skip to content

Linux Foundations / Find your way around Linux ยท Step 21 of 63

Lesson: cp (Copy)Switch
โ† Linux Foundations

Shell and files

cp (Copy)

Copy files and directories with cp without accidentally overwriting data.

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.txt

Success 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.txt

You 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:

  • -i asks before overwriting.
  • -n does not overwrite at all.
$ cp -i report.txt report-backup.txt
cp: overwrite 'report-backup.txt'? n

Some 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 backup

If 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

  1. Create a file and copy it to a new name.
  2. Copy it again with -i and answer n.
  3. Make a directory and copy the file into it.
  4. Copy that directory with cp -r twice and inspect the result with ls -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.