VPS Hosting

VPS Hosting

Buy Now

How to use cp or copy command in Linux

Copying files and directories is a core task for Linux administrators. 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 in it entirety can make a real impact on your efficiency.

In this guide we’ll go over practical cp usage with examples for different tasks, ensuring you’re well-equipped for managing any Linux system.

Copy multiple files simultaneously

When you need to copy several files into one destination, cp allows you to specify multiple source files followed by the target directory. This command copies both file1.txt and file2.txt into the Backup directory.

cp /home/cpusername/public_html/index.html /home/cpusername/public_html/page1.html /home/cpusername/backup/

Copying an entire directory (recursively)

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. This creates a full copy of the Documents directory inside Backup, including all subdirectories and files.

cp -r /home/cpusername/public_html /home/cpusername/backup/

Preserving original file or directory attributes

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. The copied file in backup will retain the same attributes (incl Metadata) as the original.

cp -p /home/cpusername/public_html/index.html /home/cpusername/backup/

Overwriting files with confirmation

Accidental overwrites can lead to data loss. The -i (interactive) option prompts for confirmation before replacing any existing files at the destination. In the example below if myfile.txt already exists in the Backup directory, the system will ask whether to overwrite it.

cp -i /home/cpusername/public_html/index.html /home/cpusername/backup/

Combining multiple flags

Most of the time you’ll want to use multiple flags together as it gives you more control and saves time compared to clicking through a file manager. In this example, doing a recursive, interactive copy that also keeps file details means you won’t lose anything important, and it’ll ask before overwriting stuff, preventing any missteps.

cp -rpi /home/cpusername/public_html /home/cpusername/backup/

When to use rsync Instead

While cp handles basic file copying well, consider using the rsync command for advanced scenarios between servers, bandwidth efficiency, and progress tracking.