How to Copy Files and Directories in CentOS

How to Copy Files and Directories in CentOS

By: ZebraHost

It’s very easy to copy a file or directory in CentOS by using the cp command. However, the command will change slightly depending on whether you are moving a file or a directory. Files can simply be copied while directories will require -r to be added to the command which copies the targeted directory as well as it’s contents.

Copying a File

Copying a Single File into a Directory

to copy a single file instead of a directory, simply use the cp "file to copy" "destination"

In this example, I will copy a file called “testfile” to an existing directory called “testfolder

image

to copy “testfile” into “testfolder” we are going to type the following command:

cp testfile testfolder

image

As you can see from the above image, “testfile” was successfully copied from its initial directory into “testfolder”.

Copying a Single File into the Same Directory as Another File

If you need to make a clone of a file within the same directory, the cp command will also work.

In this example I will make a clone of “testfile” and call it “testfile2

image

Copying a Single File into the Previous Directory

there might be times that a particular file Needs to be copied to a previous directory. Often, this can be easily achieved by copying the file into the previous directory and navigating as far back as needed to with mv, which will eventually place the file where it needs to be. This is done with .. much like when using the cd command to navigate.

Here is an example of moving testfile the previous directory using this function.

image

Copying a Directory

The same commands from above apply to directories. However, when copying entire directories (regardless if they contain files) you will need to add r or recursive to the command.

Command: cp -r "directory" "directory destination"

Here is an example of copying the “testfolder” directory into “copydestination

image

The “cp” command is universal across all Linux systems and will work with popular distros such as Ubuntu, Debian, etc.