The cp
(copy) command in Linux/Unix is used to copy files and directories from one location to another. It is one of the most commonly used commands for file management and supports a variety of options for preserving file attributes, copying directories, and handling permissions.
In this blog, we will explore the syntax, options, and examples of the cp
command in Linux/Unix.
1. Syntax of the cp
Command
The basic syntax of the cp
command is:
cp [OPTIONS] source destination
source
– The file or directory you want to copy.destination
– The target location where the file/directory will be copied.OPTIONS
– Various flags that modify the command behavior.
2. Basic cp
Command Examples
a) Copy a File
To copy a file from one location to another, use:
cp file1.txt /home/user/Documents/
This copies file1.txt
to the Documents directory.
b) Copy a File with a New Name
To copy a file and rename it:
cp file1.txt newfile.txt
This creates a duplicate named newfile.txt
.
c) Copy Multiple Files
You can copy multiple files at once:
cp file1.txt file2.txt file3.txt /home/user/Backup/
This copies all specified files to the Backup directory.
3. Copying Directories
By default, cp
does not copy directories unless you use the -r
(recursive) option.
a) Copy a Directory Recursively
cp -r myfolder /home/user/Backup/
This copies myfolder
and all its contents to the Backup directory.
b) Copy Directory with Hidden Files
To copy hidden files as well, use:
cp -r myfolder/.* /home/user/Backup/
This ensures hidden files (starting with .
) are copied.
4. Advanced cp
Command Options
a) Preserve File Attributes (-p
)
The -p
option retains timestamps, permissions, and ownership of the file:
cp -p file1.txt /home/user/Backup/
b) Display Copy Progress (-v
)
The -v
(verbose) option shows details of the copying process:
cp -v file1.txt /home/user/Backup/
c) Prompt Before Overwriting (-i
)
To prevent accidental overwrites, use the -i
(interactive) flag:
cp -i file1.txt /home/user/Backup/
If a file with the same name exists, it asks for confirmation before overwriting.
d) Force Overwriting (-f
)
To overwrite without confirmation, use:
cp -f file1.txt /home/user/Backup/
e) Preserve Symbolic Links (-a
)
The -a
(archive) option copies files along with symbolic links:
cp -a myfolder /home/user/Backup/
5. Copy Files Based on Modification Time
To copy only newer versions of a file (avoiding unnecessary overwrites), use:
cp -u file1.txt /home/user/Backup/
This copies file1.txt
only if it’s newer than the existing one in the destination.
6. Conclusion
The cp
command in Linux is a powerful tool for copying files and directories efficiently. By mastering its options like -r
for directories, -p
for attributes, and -i
for confirmation, you can handle file management with greater control.
🚀 Start using these cp
command variations in your Linux workflow and make file handling easier!
Have any questions? Let us know in the comments!