Linux distributions provide the cp
command in order to copy files and directories. The name cp comes from the copy
. The cp command can be used to copy single or multiple files and folders in a recursive manner by including the child files and directories.
cp Command Syntax
The cp command syntax is like below.
cp OPTION SOURCE DESTINATION
- OPTION is cp options for recursive etc.operations.
- SOURCE is the source file or directory.
- DESTINATION is the destination file or directory.
Copy File
In the following example, we will copy the file named db.txt
into the destination with the name of db_backup.txt
.
$ cp db.txt db_backup.txt
Copy Multiple Files
We can copy multiple files into the specified destination path or directory. In the following example, we will copy db.txt
, test.txt
, names.txt
into the destination path/home/ismail/backup
.
$ cp db.txt test.txt names.txt /home/ismail/backup
Copy Directory
The cp command can be also used to copy the source directory to the destination directory.
$ cp /home/backup /mnt/backup
Copy Child Directories Recursively
Directories may include child directories or files. In order to copy these child directories or files to the destination, the recursive option should be provided. The -R
is used as the recursive option.
$ cp -R /home/ismail /mnt/backup
Preserve Modification, Access, and Ownership
Every file and directory has attributes like modification date, access date, ownership, etc. These attributes are generated during the copy operation. But if we need to preserve these attributes like modification date, access date, ownership, etc. the preserve option should be used. The -p
is used as a preserve option.
$ cp -R -p /home/ismail /mnt/backup
Interactive Copy
During file and directory copy operation multiple files can be copied and we may need to approve every file or directory copied. We can execute the copy operation as interactive by approving or denying every copy of file or directory. The -i
option is used for interactive copy.
$ cp -R -i /home/ismail /mnt/backup
Force Copy
If the destination file or directory exist the cp command omits the copy for this file or directory. Simply cp command does not overwrite by default. If we need to overwrite destination files or directories we should force the copy operation with the -f
option like below.
$ cp -R -f /home/ismail /mnt/backup
Copy File If Source Is Newer Than Destination
The cp command provides the ability to copy if the source file is newer than the destination file. Especially updating files with the same name but different contents the modification date is important. The -u
option can be used to update the same file name for newer ones. If the destination file is newer than the source file the source file is not copied.
$ cp -u db.txt backupdb.txt