Copying Files
Need a backup? Want to duplicate a template? Time to learn cp.
Basic Copy
Syntax: cp source destination
Copy to a Directory
If the destination is a directory, the file keeps its name.
Copy Multiple Files
When copying multiple files, the destination must be a directory.
Copy and Rename
This is the standard pattern for quick backups.
Backup Before Editing
Before editing important config files:
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:
You need -r (recursive):
Trailing Slash Behavior
Watch out:
cp -r mydir backup/→ Createsbackup/mydir/cp -r mydir/ backup/→ Same resultcp -r mydir/* backup/→ Copies contents, not the folder itself
Useful Flags
-i (Interactive)
Ask before overwriting:
-n (No Clobber)
Never overwrite:
-v (Verbose)
Show what's happening:
-p (Preserve)
Keep original timestamps and permissions:
-a (Archive)
The ultimate preservation flag. Combines -r + -p + preserves links:
Use -a for backups where you want an exact replica.
Common Patterns
Quick Backup
cp config.json{,.bak} # Creates config.json.bak
cp -a project project.backup
Copy Template
cp template.html newpage.html
Backup Config Before Edit
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
- A new file is created at the destination
- Data is copied from source to destination
- The original file is unchanged
- By default, the copy gets a new timestamp
How do you copy a directory and all its contents?
Key Takeaways
cp source destinationcopies files-ris required for directories-iprompts 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.