cp ‐ #files - five4nets/Linux-Knowledgebase GitHub Wiki
cp
Command Tutorial
Linux The cp
command in Linux is used to copy files and directories from one location to another. It is a fundamental command-line tool for file management, allowing users to create duplicates of files or directories while preserving their content and, optionally, their attributes. This tutorial explains the cp
command, its syntax, options, and provides practical examples.
Table of Contents
Syntax
The basic syntax of the cp
command is:
cp [options] source destination
source
: The file or directory to be copied.destination
: The location where the file or directory will be copied.options
: Modifiers that change the behavior of the command.
Common Options
Here are some commonly used options for the cp
command:
Option | Description |
---|---|
-r or --recursive |
Copy directories recursively, including all contents and subdirectories. |
-v or --verbose |
Display detailed output of the copy process. |
-i or --interactive |
Prompt before overwriting existing files. |
-p or --preserve |
Preserve file attributes like timestamps, permissions, and ownership. |
-b or --backup |
Create a backup of the destination file before overwriting. |
-u or --update |
Copy only if the source file is newer than the destination or if the destination does not exist. |
-a or --archive |
Preserve as much as possible of the file structure and attributes, including symbolic links. |
Examples
Copying a Single File
To copy a single file to another location:
cp document.txt /home/user/backup/
This copies document.txt
from the current directory to /home/user/backup/
.
Copying Multiple Files
To copy multiple files to a directory:
cp file1.txt file2.txt file3.txt /home/user/backup/
This copies file1.txt
, file2.txt
, and file3.txt
to the /home/user/backup/
directory.
Copying a Directory
To copy a directory and its contents, use the -r
option:
cp -r /home/user/documents/ /home/user/backup/
This recursively copies the documents
directory and all its contents to /home/user/backup/
.
Copying with Verbose Output
To see the files being copied, use the -v
option:
cp -v document.txt /home/user/backup/
Output:
'document.txt' -> '/home/user/backup/document.txt'
Preserving File Attributes
To preserve file attributes like timestamps and permissions:
cp -p document.txt /home/user/backup/
This ensures the copied file retains the original file's metadata.
Interactive Copying
To avoid accidentally overwriting files, use the -i
option:
cp -i document.txt /home/user/backup/
If document.txt
already exists in the destination, the command prompts for confirmation:
cp: overwrite '/home/user/backup/document.txt'? y
Type y
to overwrite or n
to skip.
Copying with Backup
To create a backup of the destination file before overwriting:
cp -b document.txt /home/user/backup/
If document.txt
exists in the destination, a backup is created (e.g., document.txt~
).