Copying Files (cp)
The cp command copies files and directories. It's one of the most essential file operations.
Basic Usage
cp source destination
Copying Files
Copy to Same Directory (different name)
cp file.txt file_backup.txt
Copy to Different Directory
cp file.txt /path/to/destination/
cp file.txt /path/to/destination/newname.txt
cp Options
| Option | Description |
|---|---|
-r | Recursive (for directories) |
-i | Interactive (prompt before overwrite) |
-v | Verbose (show files being copied) |
-p | Preserve permissions and timestamps |
-n | Don't overwrite existing files |
Copying Directories
Use -r (recursive) for directories:
cp -r source_dir destination_dir
Exercise: Copy a File
Copy the notes.txt file from documents to a new file called notes_copy.txt:
Copying Multiple Files
Copy multiple files to a directory:
cp file1.txt file2.txt file3.txt destination/
Or use wildcards:
cp *.txt backup/ # All .txt files
cp documents/*.pdf archive/ # All PDFs from documents
Interactive Mode
Prevent accidental overwrites:
cp -i source.txt existing.txt
# Prompts: overwrite 'existing.txt'?
Preserve Attributes
Keep original permissions and timestamps:
cp -p original.txt copy.txt
Common Patterns
Backup a File
cp config.txt config.txt.bak
cp -p important.txt important.txt.backup
Copy Directory Contents
cp -r project/* backup/ # Copy contents only
cp -r project backup/ # Copy directory itself
Troubleshooting
| Error | Cause | Solution |
|---|---|---|
omitting directory | Copying dir without -r | Use cp -r |
cannot stat | Source doesn't exist | Check the path |
Permission denied | No read/write access | Check permissions |
Key Takeaways
cp source destinationcopies files- Use
-rto copy directories recursively - Use
-ito prompt before overwriting - Use wildcards to copy multiple files
- Always verify paths before copying

