In this guide, we focus on cp command in Linux/Unix systems. cp command – short for copy – is a command used for copying files and directories in Linux. It’s a command that is widely used both by Linux beginners and seasoned experts on a regular basis. Let’s dive in and see how this command is used.

Linux cp command example

The basic command structure of cp command is as follows:

Let’s look at some examples of using cp command to copy files and folders in Linux.

Copy a file from current directory to subdirectory

To copy a file from the present working directory to a subdirectory use the syntax below:

Example

For example, to copy a file file1.txt to a sub directory called data execute the cp command as follows. Later use the ls command to verify the existence of the file in the directory.

Sample output

copy-file-to-a-subdirectory

Copy a file from current directory to an absolute destination path

To copy a file from the present working directory to a different destination directory or absolute path, use the syntax below.

Example

Output

Copy a file from absolute source path to an absolute path

To copy a file(s) from a different file path to another absolute path use the syntax:

Example

Sample output

Copy multiple files

Linux cp command also allows you to copy more than one file at a go using the syntax below.

Example

Sample output

Copy file with verbose output

To display verbose output, use the -v flag as shown.

Sample output

copy-with-verbose-output

Copy files interactively

To copy files interactively i.e to provoke a prompt from the Linux shell, use the -i flag as shown.

Sample output

Copy files associated with a certain file extension

If you wish to copy a number of files with the same file extension, say .txt or .pdf follow the example below.

Linux Copy Directory Recursively

If you want to copy a directory alongside all its contents, use the -R attribute followed by the directory name as shown.

Sample output

To copy the contents of a directory but not the directory itself, run the command as follows.

Sample output

Linux man cp

We can run man cp command to look at the documentation of cp command. This is useful to find out the right options to use with the cp command.

Sample output

Summary

Linux cp command helps us in copying files and folders easily. It’s one of the most used commands. The man page of cp command is very helpful in finding the suitable options to use.

By admin

Leave a Reply