Linux cp
Command
The cp
command in Linux, short for "copy," is a powerful utility
that allows users to copy files and directories. Whether you need to
duplicate
files for backup, create backups, or distribute files across your system,
cp
is an essential tool in your Linux toolbox. In this blog
post,
we'll explore the various aspects of the cp
command, its usage,
options, and some practical examples to enhance your file management skills.
Basic Usage
The basic syntax of the cp
command is straightforward:
bashcp <source> <destination>
Here's how you can use it to copy a file:
bashcp file.txt /path/to/destination/
To copy a directory and its contents:
bashcp -r directory/ /path/to/destination/
Common Options
The cp
command supports various options to modify its behavior:
-i
or--interactive
: Prompts before overwriting any existing files.
bashcp -i file.txt /path/to/destination/
-r
or--recursive
: Allows copying directories and their contents recursively.
bashcp -r directory/ /path/to/destination/
-u
or--update
: Copies files only if the source is newer than the destination or if the destination is missing.
bashcp -u file.txt /path/to/destination/
-v
or--verbose
: Provides verbose output, showing the files being copied.
bashcp -v file.txt /path/to/destination/
Overwriting Files
By default, cp
will overwrite the destination file if it already
exists. To avoid overwriting, you can use the -i
option to
prompt
for confirmation before overwriting, as shown in the common options section.
Preserving File Attributes
The cp
command does not preserve file attributes (such as
permissions and timestamps) by default. To preserve these attributes, use
the
-p
option:
bashcp -p file.txt /path/to/destination/
Practical Examples
-
Copying Files:
bashcp file.txt /path/to/destination/
-
Copying Files Verbosely:
bashcp -v file.txt /path/to/destination/
-
Copying Directories Recursively:
bashcp -r directory/ /path/to/destination/
-
Prompting before Overwriting:
bashcp -i file.txt /path/to/destination/
-
Preserving File Attributes:
bashcp -p file.txt /path/to/destination/