The cp
command is used to copy files or directories from a source location to a destination location. The cp
command is a basic command that is used frequently in Linux systems administration.
Overview
The basic syntax of the cp
command is:
cp [options] source destination
Here, source
can be a file or a directory, and destination
can be a file or a directory. If source
is a file, then destination
must be a file. If source
is a directory, then destination
must be a directory.
Copying a file
To copy a file, use the following syntax:
cp file.txt /path/to/destination/
This will copy the file file.txt
to the /path/to/destination/
directory.
Copying a directory
To copy a directory, use the following syntax:
cp -r /path/to/source/ /path/to/destination/
This will copy the entire directory source
to the destination
directory. The -r
option is used to copy directories recursively.
Overwriting an existing file
If the destination file already exists, cp
will overwrite it without prompting for confirmation. To avoid this, use the -i
option:
cp -i file.txt /path/to/destination/
This will prompt you for confirmation before overwriting the destination file.
Preserving file attributes
To preserve the file attributes, such as permissions, ownership, and timestamps, use the -p
option:
cp -p file.txt /path/to/destination/
This will copy the file file.txt
to the /path/to/destination/
directory while preserving its attributes.
Options
Here is a list of the most commonly used options for the cp
command:
Option | Description |
---|---|
-r |
Copy directories recursively |
-i |
Prompt before overwriting an existing file |
-p |
Preserve file attributes |
-v |
Display progress of the copy operation |
Troubleshooting Tips
- If you are copying a large number of files, it may take some time for the
cp
command to complete. Be patient and wait for the command to finish. - If you are copying files across different file systems, make sure that the destination file system has enough space to accommodate the files you are copying.
- If you are encountering permission errors, make sure that you have the necessary permissions to read from the source and write to the destination.
Notes
- The
cp
command does not remove the source file or directory after copying. If you want to remove the source file or directory, use therm
command. - If you are copying a large number of files, you may want to consider using the
rsync
command instead ofcp
.rsync
is a more advanced tool that is optimized for copying large amounts of data.