Copying files and directories is a core task, especially when starting out with Linux. The cp command provides fast, reliable copying with extensive customisation. This makes copying important documents or duplicating system files easier.
In this guide we’ll go over how to use cp with realistic examples for different tasks.
Use cp to copy multiple files to a single target directory, the command below will copy both index.html and about-us.html to the backup directory. This is a good example of using cp to create a quite backup of important site pages.
cp /home/cpusername/public_html/index.html /home/cpusername/public_html/about-us.html /home/cpusername/backup/
In some cases you may want to copy an entire directory and its contents, we can achieve this using the cp command with the recursive flag (-r). The example command below will copy everything in the public_html folder to the backup folder.
cp -r /home/cpusername/public_html /home/cpusername/backup/
Not to be confused with the -P flag, when the -p flag is invoked copied files will retain all of the original attributes. This includes timestamps, ownership, links and permissions. Perfect when you are creating backups as it ensure that everything copied is exactly the same as in the original. The example below shows the -p flag being used to copy index.html to the backup directory.
cp -p /home/cpusername/public_html/index.html /home/cpusername/backup/
Mistakes happen, especially when using the command line. Using the -i flag you’ll be prompted for confirmation before any files are replaced at the destination. In our example command below you if index.html exists in the backup directory you will have to confirm you want cp to run.
cp -i /home/cpusername/public_html/index.html /home/cpusername/backup/
There are a lot more flags that can be utilised with the cp command, for a full list check out the manual.
In most cases the most efficient (and safe) way of using cp is to combine multiple flags (options) together. In our example you will copy the entire directory, preserve it’s original data prompt you before overwriting.
cp -rpi /home/cpusername/public_html /home/cpusername/backup/
cp is great for copying files on a Linux system but when you need to copy between servers the rsync command is better suited.