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:
$ cp [options] source dest
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:
$ cp file directory
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.
$ cp file1.txt data
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.
$ cp file /path/to/directory
$ cp file1.txt /home/james/
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:
cp /path/to/source/file /path/to/destination/directory
$ cp /home/james/file1.txt /opt/data
Copy multiple files
Linux cp command also allows you to copy more than one file at a go using the syntax below.
$ cp file1 file2 .... /path/to/directory
$ cp file1.txt file2.txt file3.txt /home/james/
Copy file with verbose output
To display verbose output, use the
-v flag as shown.
cp -v file1.txt file2.txt /home/james
Copy files interactively
To copy files interactively i.e to provoke a prompt from the Linux shell, use the
-i flag as shown.
$ cp -i file1.txt /home/james
Copy files associated with a certain file extension
If you wish to copy a number of files with the same file extension, say
$ cp *.txt /home/james
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.
$ cp -R data /home/james
To copy the contents of a directory but not the directory itself, run the command as follows.
$ cp -R data/* /home/james
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.
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.