Skip to content

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

cp file1.txt /path/to/destination/
This command copies file1.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

cp file1.txt /path/to/destination/new_file.txt
This command copies file1.txt to the directory /path/to/destination/ and renames the copied file to new_file.txt.

Copying Multiple Files to a Directory

cp file1.txt file2.txt file3.txt /path/to/destination/
This copies file1.txt, file2.txt, and file3.txt to the directory /path/to/destination/.

Copying a Directory Recursively

cp -r directory1 /path/to/destination/
This command copies the directory directory1 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

cp -p directory1 /path/to/destination/
This command copies the directory directory1 to /path/to/destination/, preserving the original permissions and timestamps of the files and directories.

Interactive Copying

cp -i file1.txt /path/to/destination/
This command copies file1.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/


Share on Share on

Comments