cp
Command: Copying Files and Directories in Linux
Summary
The cp
command is a fundamental Linux utility used for copying files and directories from one location to another. It offers various options for controlling the copying process, such as preserving timestamps, creating symbolic links, and handling directory structures.
Introduction
The cp
command stands for "copy". It creates a duplicate of a file or directory and places it in a specified destination. This command is essential for backing up data, creating templates, and organizing files within your file system. By default, cp
overwrites existing files with the same name in the destination directory. It's a core utility, meaning it's almost always available on any Linux distribution.
Use Cases and Examples
Copying a Single File
This command copiesfile1.txt
to the directory /path/to/destination/
. The copied file will have the same name as the original. Copying a File with a New Name
This command copiesfile1.txt
to the directory /path/to/destination/
and renames the copied file to new_file.txt
. Copying Multiple Files to a Directory
This copiesfile1.txt
, file2.txt
, and file3.txt
to the directory /path/to/destination/
. Copying a Directory Recursively
This command copies the directorydirectory1
and all its contents (including subdirectories and files) recursively to /path/to/destination/
. The -r
option is crucial for copying directories. Copying a Directory and Preserving Permissions and Timestamps
This command copies the directorydirectory1
to /path/to/destination/
, preserving the original permissions and timestamps of the files and directories. Interactive Copying
This command copiesfile1.txt
to /path/to/destination/
. If a file with the same name already exists, it will prompt you to confirm whether you want to overwrite it. Commonly Used Flags
Flag | Description | Example |
---|---|---|
-r or -R | Recursive copy. Used to copy directories and their contents. | cp -r directory1 /path/to/destination/ |
-i | Interactive. Prompts the user before overwriting existing files. | cp -i file1.txt /path/to/destination/ |
-p | Preserve. Preserves the original timestamps, ownership, and permissions of the files and directories. | cp -p file1.txt /path/to/destination/ |
-f | Force. Overwrites existing files without prompting. | cp -f file1.txt /path/to/destination/ |
-u | Update. Copies a file only if the source file is newer than the destination file or if the destination file does not exist. | cp -u file1.txt /path/to/destination/ |
-l | Create hard links instead of copying. | cp -l file1.txt /path/to/destination/ |
-s | Create symbolic links instead of copying. | cp -s file1.txt /path/to/destination/ |