How to Copy a File in Bash: Simple Command and Examples
To copy a file in bash, use the
cp command followed by the source file and the destination path. For example, cp source.txt destination.txt copies the file named source.txt to destination.txt.Syntax
The basic syntax of the copy command in bash is:
cp [options] source_file destination
Here, source_file is the file you want to copy, and destination is the new file name or directory where you want to copy the file.
Options can modify the behavior, like -i to ask before overwriting.
bash
cp source_file destination
Example
This example copies a file named notes.txt to a new file named backup_notes.txt in the same directory.
bash
cp notes.txt backup_notes.txt ls -l backup_notes.txt
Output
-rw-r--r-- 1 user user 1234 Apr 27 12:00 backup_notes.txt
Common Pitfalls
Common mistakes when copying files include:
- Forgetting to specify the destination file or directory, which causes an error.
- Overwriting files without warning if
-ioption is not used. - Copying directories without
-roption, which is required for recursive copy.
Always check if the destination exists to avoid accidental data loss.
bash
cp source.txt destination.txt # Correct usage cp source.txt # Wrong: missing destination cp -i source.txt destination.txt # Safer copy with prompt before overwrite
Quick Reference
| Command | Description |
|---|---|
| cp source.txt destination.txt | Copy file to new file or location |
| cp -i source.txt destination.txt | Copy with prompt before overwrite |
| cp -r dir1 dir2 | Copy directory recursively |
| cp -v source.txt destination.txt | Copy with verbose output |
Key Takeaways
Use the cp command followed by source and destination to copy files in bash.
Add -i option to avoid overwriting files without warning.
Use -r option to copy directories recursively.
Always specify both source and destination to avoid errors.
Check the copied file exists with ls after copying.