Introduction
The commandcp(copy) is one of the most used tools in the Linux command line to duplicate files and directories. Whether you need to make a quick backup, move data between partitions or simply organize your work space, understand your options and behaviors will save you time and avoid information losses.
Basic syntax
The simplest way to usecpis:
cp origen destino
Whereorigenis the file or directory you want to copy anddestinois the location where the copy will be placed. Yeah.destinois a non-existing file name,cpcreate a new file with that name; if it already exists, it will overwrite it unless you indicate otherwise.
Most useful options
-ror-R: recursive copy, required for directories.-i: order confirmation before overwriting an existing file.-u: copy only when the origin is more new than the destination or when the destination does not exist.-v: Vertical mode, show what is being copied.-p: retains permissions, timstamps and other attributes of the original file.-a: equals-dR --preserve=all, ideal for making an identical copy of a directory.--backup[=CONTROL]: create a backup of the target file before overwriting.
Practical examples
Copy a file callednota.txtto the directory/tmp:
cp nota.txt /tmp/
Rename the file when copying it:
cp nota.txt /tmp/nota_respaldo.txt
Copy several files to a directory:
cp archivo1.txt archivo2.txt /home/usuario/documentos/
Copy full directories
To duplicate a directory and all its content you must use the option-r:
cp -r proyectos/ /var/backup/proyectos_backup
If you want to maintain the exact structure, including symbolic links and attributes, you prefer-a:
cp -a proyectos/ /var/backup/proyectos_clone
Preserve attributes and links
The option-pensures that permissions, owner, group and time marks remain identical. When working with symbolic links,-P(capital) copy the link itself, while-Lfollow the link and copy the file to which it points.
Common errors and how to avoid them
- Accidentally overwrite important files: always use
-ior create a backup with--backup. - Forget the recursive option when trying to copy a directory: the command will fail with a message like «missing directory».
- Confusion of the origin-destination order: inverting them can lead to overwriting of the origin. Always check before running.
- Copy in file systems that do not support certain attributes (e.g. FAT) can generate warnings; use
-awith caution.
Final Councils
Combinecpwith other commands using pipes for more advanced tasks, for example:
find . -name "*.log" -exec cp {} /mnt/archivos_log/ \;
This copies all the files.logfrom the current tree to a destination directory. Besides, you can create aliases in your~/.bashrcso thatcpalways ask for confirmation:
alias cp='cp -i'
Get to know each othercpIt will allow you to manage your files safely and efficiently, either on a production server or on your personal equipment.


