What is the general syntax of using the cp command in Linux
It has been discussed that the cp command is used to copy the files and directories from one location to another in Linux. So we will need paths of two different locations, one from where the file is being copied and the other, where it has to be pasted. The general syntax of using the cp command will be:
The general syntax is simple to understand, with the use of cp command, we can also use different options of copy, some of them are:
Options | Description |
---|---|
-b | This option will make the backup of all the contents of the file |
-f | This option is used to forcly copied all the contents of the file from source to destination |
-i | This option will confirm from you before copying the files by displaying a message |
-n | It will not overwrite the file if any file is already present in the destination path |
How to use the cp command in Linux
We will explore the usage of the cp command in Linux by using different examples. If we want to copy and paste the file within the same directory, we can use the cp command:
To confirm the new file has been created, we will list down the contents of the directory using the ls command:
We will use the “-i” option so that if the file is already present with the new name, it confirms from us to overwrite it or not:
In the above output, we don’t want to overwrite, so we type “n”. To copy the file, myfile.txt from home directory to Documents directory, we will use the cp command as:
We have used the “-v” option as it will tell us the details of the execution of the command and to confirm that the file has been copied, we run the command:
To create the backup of the myfile.txt, we will use the “-b” option:
We can also copy the directory with the help of cp command, for example, we will copy the directory “myDirectory” to Documents using the command:
We have used the “-r” option so if there is any directory inside the “myDirectory”, it will also be copied.
Conclusion
The cp command is used to copy the files and directories with all of their contents from one location to another. In this write-up, we have explored the utilization of the cp command-line utility with its basic options of backup, verbose, and interactive.