8 Best Examples Of Cp Command In Linux

cp Command in Linux: Syntax and Options

In Linux, cp stands for “copy” and is used to copy both files and directories, making it an absolute necessity for file management. The cp command can be used by users of all types, thanks to its simple syntax: Some of the common options to pair with the cp command in Linux are:

Best Examples of cp Command in Linux

Now that you know the syntax of the cp command, let’s look at some examples of how to use this command to copy files and directories in Linux.

1. Copy a Single File to the Destination

This is the most common use case for the cp command, i.e. to make a copy of a single file. The syntax to make a copy of a single file using the cp command is as follows: For example, to make a copy of the file “test.txt” to “destination_directory/”, use the cp command as:

2. Copy Multiple Files to the Destination

Just like you can make a copy of a single file, you can even use the cp command to copy multiple files to a destination directory: For example, to copy the files file1.txt, file2.txt, file3.txt to the “dest_directory” directory:

3. Copy a Single Directory to a Destination Directory

With the -r flag, you can use the cp command to copy the entire directory to a new destination: For example, to copy the “source_dir” directory with its contents:

4. Copy Multiple Directories to a Destination Directory

Just like you copy multiple files, much the same way you can copy multiple directories. The syntax to copy multiple directories: For example:

5. Preserve File Permissions for Copied File

Normally when you copy a file using the cp command, the copied file will have the file permissions as per the default permissions set for every new file that’s created. To preserve the original file’s permission, use the -p flag: For example, to preserve the permissions of “test.txt”, use the cp command as:

6. Avoid Overwriting the Destination File

By default, the cp command overwrites any pre-existing file in the destination with the same name. To avoid overwriting the filename, use the -n: For example, to avoid overwriting the file “test.txt” while copying:

7. Force Copy of the Source File

Sometimes the source file does not have write permissions to make a copy. In such a case, you can use the -f flag to forcefully make a copy of the source file: For example:

Sometimes, you may need to create a hard link or a symbolic link of the source file instead of actually copying the file. To create a hard link, use the -l flag and to create a symbolic link use the -s flag: OR For example, to create a symbolic link for the file “test.txt”: