Copying Files

Need a backup? Want to duplicate a template? Time to learn cp.

Basic Copy

Terminal
$cp original.txt copy.txt
$ls
copy.txt original.txt

Syntax: cp source destination

Copy to a Directory

Terminal
$cp file.txt Documents/
$ls Documents/
file.txt

If the destination is a directory, the file keeps its name.

Copy Multiple Files

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

When copying multiple files, the destination must be a directory.

Copy and Rename

Terminal
$cp config.json config.json.backup
$ls
config.json config.json.backup

This is the standard pattern for quick backups.

Backup Before Editing

Before editing important config files:

hljs bash
cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak

If you break something, you can restore it.

Copying Directories: The -r Flag

cp alone won't copy directories:

Terminal
$cp mydir/ backup/
cp: -r not specified; omitting directory 'mydir/'

You need -r (recursive):

Terminal
$cp -r mydir/ backup/
$ls backup/
mydir

Trailing Slash Behavior

Watch out:

  • cp -r mydir backup/ → Creates backup/mydir/
  • cp -r mydir/ backup/ → Same result
  • cp -r mydir/* backup/ → Copies contents, not the folder itself

Useful Flags

-i (Interactive)

Ask before overwriting:

Terminal
$cp -i file.txt existing.txt
cp: overwrite 'existing.txt'? y

-n (No Clobber)

Never overwrite:

Terminal
$cp -n file.txt existing.txt
(silently does nothing if file exists)

-v (Verbose)

Show what's happening:

Terminal
$cp -v file.txt Documents/
'file.txt' -> 'Documents/file.txt'

-p (Preserve)

Keep original timestamps and permissions:

Terminal
$cp -p original.txt copy.txt

-a (Archive)

The ultimate preservation flag. Combines -r + -p + preserves links:

Terminal
$cp -a /var/www /backup/www
(exact copy, permissions and all)

Use -a for backups where you want an exact replica.

Common Patterns

Quick Backup

hljs bash
cp config.json{,.bak}     # Creates config.json.bak
cp -a project project.backup

Copy Template

hljs bash
cp template.html newpage.html

Backup Config Before Edit

hljs bash
sudo cp /etc/nginx/nginx.conf /etc/nginx/nginx.conf.$(date +%Y%m%d)

This creates nginx.conf.20240114 - dated backups.

What Happens When Copying

  1. A new file is created at the destination
  2. Data is copied from source to destination
  3. The original file is unchanged
  4. By default, the copy gets a new timestamp
Knowledge Check

How do you copy a directory and all its contents?

Key Takeaways

  • cp source destination copies files
  • -r is required for directories
  • -i prompts before overwriting
  • -a (archive) preserves everything - best for backups
  • Always backup configs before editing: cp file file.bak

Next: moving and renaming files with mv.