Working with files

Linux commands: cp

Learn how the Linux cp command copies files from one place to another, and how the -r recursive option lets you copy entire folders and their contents.

You can copy a file using the cp command. You give it the file to copy and the name of the copy:

cp report.txt report-backup.txt

Now you have two files with the same content. They are independent: edit one, and the other doesn’t change.

If the destination is a folder, the copy goes inside it and keeps the original name:

cp report.txt backups/

This creates backups/report.txt. The folder must already exist, though. If it doesn’t, cp stops:

cp: directory backups does not exist

Run mkdir backups first, then copy.

To copy a folder, you need the -R option, which copies the folder and everything inside it, recursively:

cp -R site site-backup

Forget the option and cp refuses to touch the folder:

cp site site-backup
cp: site is a directory (not copied).

Nothing happens, which is a good kind of failure. You just add -R and run it again. You’ll also see -r in the wild, which does the same thing on Linux and macOS.

Now the part that deserves attention: what already exists at the destination. Plain cp overwrites an existing file without asking. If report-backup.txt already existed, it’s gone, replaced by the new copy, and there’s no undo.

When I copy things by hand I add -i, which asks before overwriting:

cp -i report.txt report-backup.txt
overwrite report-backup.txt? (y/n [n])

cp -n goes one step further and never overwrites, it just skips files that already exist.

A copy is a new file, so it gets a fresh timestamp and you as the owner. If you want the copy to keep the original’s modification time and permissions, add -p. I use it when I move config files around and want to know when they were really last edited.

Always quote paths that contain spaces, otherwise the shell splits them into separate arguments:

cp "Quarterly report.txt" "backups/Quarterly report.txt"

Before a large recursive copy, I check two things: ls on the source to be sure I’m copying what I think, and df -h to see there’s enough disk space. And if I’ll repeat the copy over time, syncing only what changed, rsync is the better tool. cp copies everything, every time.

Try this: copy a file, then edit the original and run cmp original copy. cmp reports the first byte that differs, proof that the two files are now separate things.

Lesson completed