Cp command is used to copy files and directories to some other location.
In this tutorial, we are exploring some examples of cp command. The procedure has been implemented on Red Hat Enterprise Linux 9.
Syntax
The cp command has following syntax:
Cp [OPTIONS]. . . [Source] [Destination]
Examples of cp command in Linux
Copy file in the current working directory
This is one of the basic examples of cp command. Suppose you want to copy the content of file sample.txt to backup.txt in your current working directory. The command has following syntax.
cp sample.txt backup.txt
If the destination file is not available at the location, it will be created.
Copy the file in another directory
Alternatively, if you want to copy the file in another directory say backup directory, you would run the following command.
cp sample.txt backup/
This will copy the file sample.txt to the backup directory. Now, suppose you just want to copy the content in a new_file.txt which is located in the backup directory. Run:
cp sample.txt backup/new_file.txt
Do not overwrite the file
By default, the file destination file is overwritten if already exists. You can use the -n parameter to tell the cp command do not overwrite the file. The command should look like the following:
cp -n sample.txt backup/new_file.txt
Ask for confirmation before copying the file
If you would like cp to ask you for confirmation before copying the file, use -i option as follows.
cp -i sample.txt backup/new_file.txt
Print verbose
You can force the cp command to print verbose output by using -v option as follows.
cp -v sample.txt backup/new_file.txt
Copy directories
You can use the -r option to copy the source directory. The command should be as follows:
cp -r pictures pictures_backup
Copy multiple files and directories
You can copy multiple source files and directories to another directory as follows:
cp sample1.txt sample2.txt sample3.txt Downloads/
Conclusion
For more help about cp, use man cp command on your terminal. Good luck!!