Frequently Used cp Command Examples in Linux
The cp command is used to copy files and directories in Linux from the command line. Here are some frequently used cp command examples in Linux.
Note: When using the cp command, especially when copying directories recursively, you should use caution. Double-checking before executing the command is always a good idea because you could unintentionally overwrite existing files.
1. Copy a file from one directory to another directory.
$cp /path/to/source/file /path/to/destination/directory/
Example:
$cp file1.txt /home/fossman/Documents/
2. Copy a file and preserve its attributes (permissions, timestamps, etc.):
$cp -p /path/to/source/file /path/to/destination/directory/
Example:
$cp -p file1.txt /home/fossman/Documents/
3. Copy a directory and its contents to another directory:
$cp -r /path/to/source/directory /path/to/destination/directory/
Example:
$cp -r /home/fossman/certs /home/fossman/Documents/
4. Copy multiple files to a directory:
$cp /path/to/source/file1 /path/to/source/file2 /path/to/destination/directory/
Example:
$ cp script1.sh script2.sh script3.sh /home/fossman/Documents/scripts/
5. Copy all files in a directory to another directory:
$cp /path/to/source/directory/* /path/to/destination/directory/
Example:
$ cp ~/projects/fossguides.local/* /var/ww/html/fossguides.local/
6. Copy all files and directories recursively from one directory to another:
$cp -r /path/to/source/directory/* /path/to/destination/directory/
Example:
$ cp -r ~/projects/fossguides.local/* /var/ww/html/fossguides.local/
View the man page for the cp command (run man cp) to see other usage possibilities. Use the comment box below to ask any queries or to express your opinions.