How to Copy Files in Linux With the cp Command
Copying files in Linux is an everyday task for many users. Whether it’s for backing up important files or transferring data between systems, the cp command is one of the most commonly used commands in Linux for the purpose of copying files. In this article, we will explore the basics of how to copy files in Linux with the cp command.
Copying a Single File
To copy a single file in Linux, the cp command is used with the following syntax:
cp source_file destination_file
In this command, replace the “source_file” with the name of the file you want to copy, and “destination_file” with the name of the new file you want to create. For example, to copy a file named “file.txt” located in the home directory to a new file named “new_file.txt”, we would use the following command:
cp ~/file.txt ~/new_file.txt
This command will create a copy of “file.txt” in the home directory with the name “new_file.txt”.
Copying Multiple Files
To copy multiple files in Linux, you can use the same cp command with the following syntax:
cp source_file1 source_file2 … source_fileN destination_directory
In this command, we need to list all the files we wish to copy followed by the name of the directory where we want to create the copy of those files. For example, to copy two files named “file1.txt” and “file2.txt” located in the home directory to a directory named “backup” located in the same directory, we would use the following command:
cp ~/file1.txt ~/file2.txt ~/backup/
This command will create copies of the specified files in the “backup” directory located in the home directory.
Preserving File Attributes
Often, it’s important to preserve the file attributes such as the original file’s timestamps, ownership, permissions, and many more. We can preserve these attributes while copying the files with the “-p” or “–preserve” option. The syntax of the command is as follows:
cp -p source_file destination_file
For example, to preserve all the attributes of the file “file1.txt” while copying it to a new file “new_file1.txt”, we would use the following command:
cp -p file1.txt new_file1.txt
Copying Directories
Copying directories is a bit different than copying files because directories can contain multiple files and subdirectories. To copy a directory in Linux, we use the “-r” or “–recursive” option with the cp command. The syntax of the command is as follows:
cp -r source_directory destination_directory
For example, to copy all files and subdirectories from a directory named “src” located in the home directory to a new directory named “dst” located in the same directory, we would use the following command:
cp -r ~/src/ ~/dst/