Copying files and directories is a core task in Linux administration, and the cp command provides a fast, reliable way to do it. Whether backing up important documents or duplicating system files, understanding the cp command and it’s different options will improve your efficiency and reduce errors.
This guide covers practical cp usage examples for different tasks, ensuring you’re well-equipped to manage files on any Linux system.
When you need to copy several files into one destination, cp allows you to specify multiple source files followed by the target directory.
Example:
cp /home/user/Documents/file1.txt /home/user/Documents/file2.txt /home/user/Backup/
This command copies both file1.txt and file2.txt into the Backup directory.
To duplicate a folder and everything inside it, use the -r (recursive) option. Without it, the command will fail when attempting to copy a directory.
Example:
cp -r /home/user/Documents /home/user/Backup/
This creates a full copy of the Documents directory inside Backup, including all subdirectories and files.
Use the -p
flag to maintain original file metadata, such as timestamps, ownership, and permissions. This is especially useful for backups or when replicating file structures on a new server.
Example:
cp -p /home/user/Documents/myfile.txt /home/user/Backup/
The copied file in Backup will retain the same attributes as the original.
Accidental overwrites can lead to data loss. The -i (interactive) option prompts for confirmation before replacing any existing files at the destination.
Example:
cp -i /home/user/Documents/myf
ile.txt /home/user/Backup/
If myfile.txt already exists in Backup, the system will ask whether to overwrite it.
When to Use rsync Instead
While cp handles basic file copying well, consider using the rsync command for advanced scenarios like synchronisation between servers, bandwidth-efficient transfers, and progress tracking.