How to Use cp Command in Linux: Syntax and Examples
Use the
cp command in Linux to copy files or directories from one location to another. The basic syntax is cp [options] source destination, where you specify the file or folder to copy and where to copy it.Syntax
The basic syntax of the cp command is:
cp: The command to copy files or directories.[options]: Optional flags to modify behavior (like recursive copy).source: The file or directory you want to copy.destination: The location or filename where you want to copy to.
bash
cp [options] source destination
Example
This example copies a file named file1.txt to a new file named file2.txt in the same directory.
It shows how to copy a single file and create a duplicate with a new name.
bash
cp file1.txt file2.txt ls file2.txt
Output
file2.txt
Common Pitfalls
One common mistake is forgetting to use the -r option when copying directories. Without -r, cp will not copy folders and will show an error.
Another pitfall is overwriting files without warning if you don't use the -i (interactive) option.
bash
cp myfolder backup/ # This will fail because -r is missing cp -r myfolder backup/ # Correct way to copy a directory recursively cp file1.txt file2.txt # Overwrites file2.txt silently cp -i file1.txt file2.txt # Asks before overwriting file2.txt
Output
cp: -r not specified; omitting directory 'myfolder'
# (error message)
# No output for correct commands
# Prompt appears for -i option if file2.txt exists
Quick Reference
| Option | Description |
|---|---|
| -r | Copy directories recursively |
| -i | Ask before overwriting files |
| -v | Show files being copied (verbose) |
| -u | Copy only when source is newer than destination |
| -p | Preserve file attributes (mode, ownership, timestamps) |
Key Takeaways
Use
cp source destination to copy files in Linux.Add
-r to copy directories and their contents recursively.Use
-i to avoid accidentally overwriting files without warning.The
-v option helps see what files are being copied.Always check your destination path to avoid unwanted overwrites.