Introduction
The cp (copy) command is one of the most used tools in the Linux command line for duplicating files and directories. Whether you need to make a quick backup, move data between partitions, or simply organize your workspace, understanding its options and behaviors will save you time and prevent data loss.
Basic Syntax
The simplest way to use cp is:
cp origen destino
Where origen is the file or directory you want to copy and destino is the location where the copy will be placed. If destino is a nonexistent filename, cp will create a new file with that name; if it already exists, it will be overwritten unless you indicate otherwise.
Most Useful Options
-ror-R: recursive copy, necessary for directories.-i: prompts for confirmation before overwriting an existing file.-u: copies only when the source is newer than the destination or when the destination does not exist.-v: verbose mode, shows what is being copied.-p: preserves permissions, timestamps, and other attributes of the original file.-a: equivalent to-dR --preserve=all, ideal for making an identical copy of a directory.--backup[=CONTROL]: creates a backup of the destination file before overwriting it.
Practical Examples
Copy a file named nota.txt to the /tmp directory:
cp nota.txt /tmp/
Renaming the file while copying:
cp nota.txt /tmp/nota_respaldo.txt
Copying multiple files to a directory:
cp archivo1.txt archivo2.txt /home/usuario/documentos/
Copying Entire Directories
To duplicate a directory and all its contents, you must use the -r option:
cp -r proyectos/ /var/backup/proyectos_backup
If you wish to maintain the exact structure, including symbolic links and attributes, -a is preferred:
cp -a proyectos/ /var/backup/proyectos_clone
Preserving Attributes and Links
The -p option ensures that permissions, owner, group, and timestamps remain identical. When working with symbolic links, -P (uppercase) copies the link itself, while -L follows the link and copies the file it points to.
Common Mistakes and How to Avoid Them
- Accidentally overwriting important files: always use
-ior create a backup with--backup. - Forgetting the recursive option when trying to copy a directory: the command will fail with a message like ‘skipping directory’.
- Confusing source‑destination order: reversing them can lead to overwriting the source. Always verify before executing.
- Copying to filesystems that do not support certain attributes (e.g., FAT) may produce warnings; use
-awith caution.
Final Tips
Combine cp with other commands via pipes for more advanced tasks, for example:
find . -name "*.log" -exec cp {} /mnt/archivos_log/ \;
This copies all .log files in the current tree to a destination directory. Additionally, you can create an alias in your ~/.bashrc so that cp always prompts for confirmation:
This post is also available in ESPAÑOL.