In the world of Linux, there are severalessential Linux Terminal commandsthat can make your workflow effortless. One such command is the cp command, which helps you quickly copy files and directories on your Linux system. In this article, we will discuss some examples of how to use the cp command in Linux.
cp Command in Linux: Syntax and Options
In Linux, cp stands for “copy” and is used to copy both files and directories, making it an absolute necessity for file management. The cp command can be used by users of all types, thanks to its simple syntax:
Now that you know the syntax of the cp command, let’s look at some examples of how to use this command tocopy files and directories in Linux.
This is the most common use case for the cp command, i.e. to make a copy of a single file. The syntax to make a copy of a single file using the cp command is as follows:
For example, to make a copy of the file “test.txt” to “destination_directory/”, use the cp command as:
Just like you can make a copy of a single file, you can even use the cp command to copy multiple files to a destination directory:
For example, to copy the files file1.txt, file2.txt, file3.txt to the “dest_directory” directory:
With the -r flag, you can use the cp command to copy the entire directory to a new destination:
For example, to copy the “source_dir” directory with its contents:
Just like you copy multiple files, much the same way you can copy multiple directories. The syntax to copy multiple directories:
For example:
Normally when you copy a file using the cp command, the copied file will have the file permissions as per the default permissions set for every new file that’s created. To preserve the original file’s permission, use the -p flag:
For example, to preserve the permissions of “test.txt”, use the cp command as:
By default, the cp command overwrites any pre-existing file in the destination with the same name. To avoid overwriting the filename, use the -n:
For example, to avoid overwriting the file “test.txt” while copying:
Sometimes the source file does not have write permissions to make a copy. In such a case, you can use the -f flag to forcefully make a copy of the source file:
For example:
Sometimes, you may need to create a hard link or a symbolic link of the source file instead of actually copying the file. To create a hard link, use the -l flag and tocreate a symbolic linkuse the -s flag:
OR
For example, to create a symbolic link for the file “test.txt”:
Bringing the latest in technology, gaming, and entertainment is our superhero team of staff writers. They have a keen eye for latest stories, happenings, and even memes for tech enthusiasts.