How to copy files & directories in Linux terminal?


Gaming Laptop Series

Copying files and directories in Linux is one of the most common tasks. If you are using a graphical desktop environment then you can easily copy files or directories using a file manager.

Now when it comes to copying files or directories using the command line interface it becomes a little bit tricky especially for those who are new to the Linux terminal.

Linux or Unix provides a command called cp which can be used to copy files & directories. So today we will discuss the usage of the cp command with some examples.

Syntax of cp command

How to use the cp command in Linux terminal is given below –

cp [options] source(s) destination

You can see detailed options on the man page of the cp command.

How to copy a file to another file

If you pass source and destination both as files then the cp command will copy the content of the first file to the second one. If the second file doesn’t exist the command will create a new file.

Now use the following command to copy the content of one file to another file –

cp file1.txt testfile.txt

Here the content of file1.txt will be copied to testfile.txt

How to copy one directory to another directory

If you want to copy the files or directories inside a directory to another directory then you need to use an additional option -R to recursively copy the files and directories with the cp command.

Now use the following command in your terminal –

cp -R dir testdir

Here the files and directories inside the directory dir will be copied to testdir.

How to copy multiple files to a directory

If you are passing multiple source files and directories then you should have a directory as a destination. Use the option -r to copy files and directories with the cp command.

For example –

cp -r dir1 file1.txt file2.txt testdir

Once the above command gets executed the directory dir1 files file1.txt and file2.txt will be copied to the directory testdir.

To know more about the usage of the cp command and the options that can be used with this command see its manual page. Run the following command to see the man page –

man cp

Conclusion

You have seen the usage of the cp command in this article. Now if you have a query related to this then write us in the comments below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.