cp
- Copy Files
1. Introduction
The cp
command is a cornerstone of file management in Linux and Unix-like systems, enabling users to copy files and directories efficiently. Whether duplicating a configuration file, backing up data, or organizing project folders, cp
offers the flexibility needed for these tasks. This guide provides a comprehensive overview of the cp
command, structured to match the format of the ls
and mv
command guides. It includes detailed examples with a test directory setup, answers to popular questions from forums, and validation against the official GNU Coreutils documentation (cp(1) - Linux manual page).
2. Basic Syntax
The cp
command supports multiple syntax patterns for different copying scenarios:
2.1 Copy a single SOURCE to a DESTination file:
cp [OPTION]... SOURCE DEST
- If
DEST
is an existing file, it’s overwritten unless options like-i
(interactive) or-n
(no-clobber) are used. - If
DEST
is a directory,SOURCE
is copied into it with the same name. - If
DEST
doesn’t exist, a new file is created.
2.2 Copy multiple SOURCE files into a DIRECTORY:
cp [OPTION]... SOURCE... DIRECTORY
- Copies all
SOURCE
files into an existingDIRECTORY
.
2.3 Alternative syntax using -t:
cp [OPTION]... -t DIRECTORY SOURCE...
Specifies the destination directory first, useful for scripts.
[OPTION]...
: Flags like-r
(recursive) or-p
(preserve attributes).SOURCE
: File or directory to copy.DEST
: Destination file or path.DIRECTORY
: Target directory for multiple sources.
3. Key Options Explained (with Examples)
To demonstrate cp
, let’s set up a test environment:
# Create and navigate to a test directory
$ mkdir cp_test_dir
$ cd cp_test_dir
# Create sample files
$ echo "This is file A." > fileA.txt
$ echo "This is file B." > fileB.log
$ touch empty_file
# Create a subdirectory with a file
$ mkdir subdir
$ echo "Subdir file." > subdir/sub_file.txt
# Create a symbolic link
$ ln -s fileB.log link_to_fileB
# Create a file with spaces in the name
$ echo "File with spaces." > "file with spaces.txt"
# Verify setup by listing all files and subdirectories recursively with details
$ ls -lR
Output:
.:
total 16
-rw-r--r-- 1 user user 0 May 4 18:54 empty_file
-rw-r--r-- 1 user user 16 May 4 18:54 fileA.txt
-rw-r--r-- 1 user user 16 May 4 18:54 fileB.log
-rw-r--r-- 1 user user 20 May 4 18:54 file with spaces.txt
lrwxrwxrwx 1 user user 9 May 4 18:54 link_to_fileB -> fileB.log
drwxr-xr-x 2 user user 4096 May 4 18:54 subdir
./subdir:
total 4
-rw-r--r-- 1 user user 13 May 4 18:54 sub_file.txt
3.1 Copying a Single File
Duplicate fileA.txt
as fileA_copy.txt
:
# Copy fileA.txt to a new file named fileA_copy.txt
$ cp fileA.txt fileA_copy.txt
# List the directory contents to verify the copy was created
$ ls
Output:
empty_file fileA_copy.txt fileA.txt fileB.log file with spaces.txt link_to_fileB subdir
Explanation: The cp
command creates fileA_copy.txt
with the same content as fileA.txt
. The directory now includes the new file.
3.2 Copying a File into a Directory
Copy fileB.log
into subdir
:
# Copy fileB.log into the subdir directory
$ cp fileB.log subdir/
# List the contents of subdir to verify the file was copied
$ ls subdir/
Output:
fileB.log sub_file.txt
Explanation: fileB.log
is copied into subdir/
, where it appears alongside sub_file.txt
. The original file remains unchanged.
3.3 Copying Multiple Files into a Directory
Copy fileA.txt
and empty_file
into subdir
:
# Copy fileA.txt and empty_file into the subdir directory
$ cp fileA.txt empty_file subdir/
# List the contents of subdir to verify both files were copied
$ ls subdir/
Output:
empty_file fileA.txt fileB.log sub_file.txt
Explanation: Both fileA.txt
and empty_file
are copied into subdir/
, adding to its contents. The source files remain in the parent directory.
4. Key Options Explained (with Examples)
This section lists all key options, including advanced ones previously under “Advanced/Other Options”, with detailed examples using the test environment. Each example includes the command, output, and an explanation of the directory structure change.
4.1 -r, -R, —recursive: Copy directories recursively
Description: Copies directories and their contents, including subdirectories and files, recursively.
Example:
# Copy the subdir directory and all its contents recursively to a new directory named subdir_copy $ cp -r subdir subdir_copy # List the current directory to see the new subdir_copy directory $ ls # List the contents of subdir_copy to verify the recursive copy $ ls subdir_copy/
Output:
empty_file fileA_copy.txt fileA.txt fileB.log file with spaces.txt link_to_fileB subdir subdir_copy empty_file fileA.txt fileB.log sub_file.txt
Explanation: The
subdir
directory, including all its files, is copied tosubdir_copy
. The new directorysubdir_copy
appears in the parent directory with identical contents.
4.2 -t, —target-directory=DIR: Copy all SOURCE arguments into DIR
Description: Specifies the destination directory first, useful for scripts or when copying multiple files.
Example:
# Copy fileA.txt and empty_file into the subdir_copy directory using the -t option $ cp -t subdir_copy/ fileA.txt empty_file # List the contents of subdir_copy to verify the files were copied $ ls subdir_copy/
Output:
empty_file fileA.txt fileB.log sub_file.txt
Explanation:
fileA.txt
andempty_file
are copied intosubdir_copy/
, adding to its existing contents. This syntax is equivalent tocp fileA.txt empty_file subdir_copy/
.
4.3 -v, —verbose: Explain what is being done
- Description: Displays a message for each file copied, showing the source and destination.
- Example:
Output:# Copy fileA.txt to fileA_verbose_copy.txt and display a message confirming the copy operation $ cp -v fileA.txt fileA_verbose_copy.txt
Explanation: A new file'fileA.txt' -> 'fileA_verbose_copy.txt'
fileA_verbose_copy.txt
is created, and the verbose output confirms the copy operation. The parent directory now includes this new file.
4.4 -i, —interactive: Prompt before overwrite
Description: Prompts for confirmation before overwriting an existing file, preventing accidental data loss.
Example:
# Set up: copy fileA.txt into subdir_copy to ensure it exists there $ cp fileA.txt subdir_copy/ # Attempt to copy fileB.log to subdir_copy/fileA.txt with a prompt before overwriting $ cp -i fileB.log subdir_copy/fileA.txt
Output:
cp: overwrite 'subdir_copy/fileA.txt'? y
Explanation: The command prompts before overwriting
subdir_copy/fileA.txt
withfileB.log
. Ify
is entered,fileA.txt
insubdir_copy/
is replaced withfileB.log
’s content; otherwise, it remains unchanged.
4.5 -n, —no-clobber: Do not overwrite existing files
Description: Prevents overwriting existing files at the destination without prompting.
Example:
# Attempt to copy fileB.log to subdir_copy/fileA.txt without overwriting the existing file $ cp -n fileB.log subdir_copy/fileA.txt # List details of subdir_copy/fileA.txt to verify it was not overwritten $ ls -l subdir_copy/fileA.txt
Output:
-rw-r--r-- 1 user user 16 May 4 18:54 subdir_copy/fileA.txt
Explanation: Since
fileA.txt
exists insubdir_copy/
, the-n
option preventsfileB.log
from overwriting it. The filesubdir_copy/fileA.txt
retains its original content.
4.6 -u, —update: Copy only when source is newer or destination is missing
Description: Copies files only if the source is newer than the destination or if the destination does not exist.
Example:
# Set up: set an older timestamp on subdir_copy/fileA.txt to make it appear older $ touch -t 202505040000 subdir_copy/fileA.txt # Copy fileA.txt to subdir_copy only if the source is newer than the destination $ cp -u fileA.txt subdir_copy/ # List details of subdir_copy/fileA.txt to verify the update $ ls -l subdir_copy/fileA.txt
Output:
-rw-r--r-- 1 user user 16 May 4 18:54 subdir_copy/fileA.txt
Explanation: Since
fileA.txt
in the parent directory is newer, it overwritessubdir_copy/fileA.txt
. If the source were older, no copy would occur.
4.7 -p, —preserve=mode,ownership,timestamps: Preserve attributes
Description: Preserves the source file’s permissions, ownership, and timestamps.
Example:
# Set up: change permissions of fileA.txt to 600 (read/write for owner only) $ chmod 600 fileA.txt # Copy fileA.txt to fileA_preserved.txt while preserving its mode, ownership, and timestamps $ cp -p fileA.txt fileA_preserved.txt # List details of both files to compare their attributes $ ls -l fileA.txt fileA_preserved.txt
Output:
-rw------- 1 user user 16 May 4 18:54 fileA.txt -rw------- 1 user user 16 May 4 18:54 fileA_preserved.txt
Explanation:
fileA_preserved.txt
is created with the same permissions (600
), ownership, and timestamps asfileA.txt
.
4.8 -a, —archive: Archive mode (recursive + preserve all)
Description: Combines recursive copying with preservation of all attributes, including permissions, timestamps, and symbolic links, ideal for backups.
Example:
# Copy subdir to subdir_archived preserving all attributes and directory structure $ cp -a subdir subdir_archived # List the contents of subdir_archived recursively with details to verify preservation $ ls -lR subdir_archived
Output:
subdir_archived: total 12 -rw-r--r-- 1 user user 0 May 4 18:54 empty_file -rw-r--r-- 1 user user 16 May 4 18:54 fileA.txt -rw-r--r-- 1 user user 16 May 4 18:54 fileB.log -rw-r--r-- 1 user user 13 May 4 18:54 sub_file.txt
Explanation:
subdir_archived
is an exact replica ofsubdir
, including all files and their attributes.
4.9 -L, —dereference: Follow symbolic links in SOURCE
Description: Copies the file a symbolic link points to, not the link itself.
Example:
# Create a new directory named copyL for this example $ mkdir copyL # Copy the target file that link_to_fileB points to into copyL instead of the symbolic link $ cp -L link_to_fileB copyL/ # List the contents of copyL with details to verify a regular file was copied $ ls -l copyL/
Output:
total 4 -rw-r--r-- 1 user user 16 May 4 18:54 link_to_fileB
Explanation:
copyL/link_to_fileB
is a regular file containing the content offileB.log
, not a symbolic link.
4.10 -P, —no-dereference: Do not follow symbolic links in SOURCE
Description: Copies the symbolic link itself (default behavior).
Example:
# Create a new directory named copyP for this example $ mkdir copyP # Copy the symbolic link link_to_fileB itself into copyP without dereferencing it $ cp -P link_to_fileB copyP/ # List the contents of copyP with details to verify the symbolic link was copied $ ls -l copyP/
Output:
total 0 lrwxrwxrwx 1 user user 9 May 4 18:54 link_to_fileB -> fileB.log
Explanation:
copyP/link_to_fileB
is a symbolic link pointing tofileB.log
, preserving the link structure.
4.11 -d: Preserve links
Description: Equivalent to
--no-dereference --preserve=links
, ensures symbolic links are copied as links during recursive copying.Example:
# Copy the symbolic link link_to_fileB to copyP/link_to_fileB_d, preserving it as a link $ cp -d link_to_fileB copyP/link_to_fileB_d # List the contents of copyP with details to see both symbolic links $ ls -l copyP/
Output:
total 0 lrwxrwxrwx 1 user user 9 May 4 18:54 link_to_fileB -> fileB.log lrwxrwxrwx 1 user user 9 May 4 18:54 link_to_fileB_d -> fileB.log
Explanation:
copyP/link_to_fileB_d
is a symbolic link, identical tolink_to_fileB
.
4.12 -l, —link: Create hard links instead of copying
Description: Creates a hard link to the source file, sharing the same data on disk, saving space but limited to the same filesystem.
Example:
# Create a hard link to fileA.txt named fileA_hardlink.txt instead of copying its data $ cp -l fileA.txt fileA_hardlink.txt # List the inode numbers of both files to confirm they share the same data $ ls -i fileA.txt fileA_hardlink.txt
Output:
123456 fileA.txt 123456 fileA_hardlink.txt
Explanation:
fileA_hardlink.txt
is a hard link with the same inode asfileA.txt
, pointing to the same data.
4.13 -s, —symbolic-link: Create symbolic links instead of copying
Description: Creates a symbolic link to the source file at the destination.
Example:
# Create a symbolic link to fileA.txt named fileA_symlink.txt instead of copying it $ cp -s fileA.txt fileA_symlink.txt # List details of fileA_symlink.txt to verify it is a symbolic link $ ls -l fileA_symlink.txt
Output:
lrwxrwxrwx 1 user user 9 May 4 18:54 fileA_symlink.txt -> fileA.txt
Explanation:
fileA_symlink.txt
is a symbolic link pointing tofileA.txt
.
4.14 —parents: Use full source path under destination directory
Description: Replicates the source file’s directory structure within the destination directory.
Example:
# Set up: create a nested directory structure source_dir/level1 $ mkdir -p source_dir/level1 # Create a sample file data.txt inside source_dir/level1 $ touch source_dir/level1/data.txt # Create a destination directory named destination_dir $ mkdir destination_dir # Copy data.txt into destination_dir while preserving its full path from source_dir $ cp --parents source_dir/level1/data.txt destination_dir/ # List the contents of destination_dir recursively to verify the structure $ ls -R destination_dir/
Output:
destination_dir/: source_dir destination_dir/source_dir: level1 destination_dir/source_dir/level1: data.txt
Explanation: The directory structure
source_dir/level1/data.txt
is recreated underdestination_dir/
.
4.15 -b, —backup: Create backups of overwritten files
Description: Creates backups of destination files before overwriting, typically with a
~
suffix.Example:
# Set up: create fileA_copy.txt with some initial content $ echo "Original content." > fileA_copy.txt # Copy fileA.txt to fileA_copy.txt and create a backup of the original fileA_copy.txt $ cp -b fileA.txt fileA_copy.txt # List the directory to see the backup file with the ~ suffix $ ls
Output:
empty_file fileA_copy.txt fileA_copy.txt~ fileA.txt fileB.log file with spaces.txt link_to_fileB subdir
Explanation:
fileA_copy.txt
is overwritten withfileA.txt
’s content, and a backupfileA_copy.txt~
is created with the original content.
4.16 —sparse=WHEN: Optimize copying sparse files
Description: Optimizes copying of sparse files (files with large zero-filled regions) to save disk space. Options include
always
,auto
, ornever
.Example:
# Create a sparse file named sparse_file with a size of 100MB but minimal actual data $ dd if=/dev/zero of=sparse_file bs=1M count=0 seek=100 # Copy sparse_file to sparse_copy while preserving its sparse nature $ cp --sparse=always sparse_file sparse_copy # List the sizes and details of both files to confirm they remain sparse $ ls -ls sparse_file sparse_copy
Output:
0 -rw-r--r-- 1 user user 104857600 May 4 18:54 sparse_copy 0 -rw-r--r-- 1 user user 104857600 May 4 18:54 sparse_file
Explanation:
sparse_copy
is a sparse file, using minimal disk space despite its large apparent size, matchingsparse_file
.
4.17 —reflink=WHEN: Use copy-on-write
Description: Uses copy-on-write on supported filesystems (e.g., Btrfs, XFS) for faster, space-efficient copies. Options include
always
,auto
, ornever
.Example (on a Btrfs filesystem):
# Copy fileA.txt to fileA_reflink.txt using copy-on-write reflink if the filesystem supports it $ cp --reflink=always fileA.txt fileA_reflink.txt # List the directory to see the new file $ ls
Output:
empty_file fileA_copy.txt fileA_reflink.txt fileA.txt fileB.log file with spaces.txt link_to_fileB subdir
Explanation:
fileA_reflink.txt
is a reflink tofileA.txt
, sharing data blocks until modified, saving space.
4.18 —preserve=ATTR_LIST: Preserve specific attributes
Description: Preserves specific attributes (e.g.,
mode
,ownership
,timestamps
,context
,links
,xattr
,all
). More granular than-p
.Example:
# Set up: change permissions of fileA.txt to 600 (read/write for owner only) $ chmod 600 fileA.txt # Copy fileA.txt to fileA_preserved_attrs.txt preserving only mode and ownership $ cp --preserve=mode,ownership fileA.txt fileA_preserved_attrs.txt # List details of both files to compare their preserved attributes $ ls -l fileA.txt fileA_preserved_attrs.txt
Output:
-rw------- 1 user user 16 May 4 18:54 fileA.txt -rw------- 1 user user 16 May 4 18:54 fileA_preserved_attrs.txt
Explanation:
fileA_preserved_attrs.txt
retainsfileA.txt
’s mode and ownership, but not necessarily timestamps unless specified.
4.19 -f, —force: Force removal of destination if it can’t be opened
Description: Removes the destination file if it cannot be opened for writing, then retries the copy. Use cautiously to avoid data loss.
Example:
# Set up: create a read-only file named protected.txt with some content $ echo "Protected content." > protected.txt # Set up: change permissions of protected.txt to 400 (read-only for owner) $ chmod 400 protected.txt # Force copy fileA.txt to protected.txt, removing the destination if it can't be opened $ cp -f fileA.txt protected.txt # List details of protected.txt to verify the copy $ ls -l protected.txt
Output:
-r-------- 1 user user 16 May 4 18:54 protected.txt
Explanation: The
-f
option removesprotected.txt
(if permissions allow) and copiesfileA.txt
to it. Without-f
, the copy might fail due to permissions.
4.20 -T, —no-target-directory: Treat destination as a file
- Description: Treats the destination as a file, not a directory, even if it exists as a directory, which can lead to errors if misused.
- Example:
Output:# Attempt to copy fileA.txt to subdir treating subdir as a file instead of a directory $ cp -T fileA.txt subdir
Explanation: The command fails becausecp: cannot overwrite directory 'subdir' with non-directory
subdir
is a directory, and-T
expects a file. Use with caution to avoid errors.
4.21 -Z, —context: Set SELinux security context
Description: Sets the SELinux security context of the destination file, useful in SELinux-enabled systems.
Example (on an SELinux-enabled system):
# Copy fileA.txt to fileA_selinux.txt and set the default SELinux security context $ cp -Z fileA.txt fileA_selinux.txt # List the SELinux context of fileA_selinux.txt to verify $ ls -Z fileA_selinux.txt
Output (example SELinux context):
-rw-r--r--. 1 user user unconfined_u:object_r:user_home_t:s0 16 May 4 18:54 fileA_selinux.txt
Explanation:
fileA_selinux.txt
is created with the default SELinux context for the destination, ensuring compatibility with SELinux policies.
5. Combining Options
Combining options allows for tailored copying operations. Below are examples demonstrating common combinations, with input commands, outputs, and explanations.
Example 5.1: Recursive Copy with Verbose Output
- Command: Copy
subdir
recursively, showing each file copied.
Output:# Copy subdir recursively to subdir_verbose_copy and display a message for each file copied $ cp -rv subdir subdir_verbose_copy
Explanation: The'subdir/empty_file' -> 'subdir_verbose_copy/empty_file' 'subdir/fileA.txt' -> 'subdir_verbose_copy/fileA.txt' 'subdir/fileB.log' -> 'subdir_verbose_copy/fileB.log' 'subdir/sub_file.txt' -> 'subdir_verbose_copy/sub_file.txt'
-r
option ensures recursive copying, and-v
displays each file as it’s copied. A new directorysubdir_verbose_copy
is created with all files fromsubdir
.
Example 5.2: Preserve Attributes and Prompt Before Overwriting
- Command: Copy
fileA.txt
tosubdir_copy/
, preserving attributes and prompting for overwrites.
Output (if# Copy fileA.txt to subdir_copy preserving attributes, prompting before overwrite, and avoiding overwrite if declined $ cp -pin fileA.txt subdir_copy/
fileA.txt
exists insubdir_copy/
):
Explanation: Thecp: overwrite 'subdir_copy/fileA.txt'? y
-p
option preserves permissions, ownership, and timestamps,-i
prompts before overwriting, and-n
ensures no overwrite if the user declines. Ify
is entered,subdir_copy/fileA.txt
is updated with preserved attributes.
Example 5.3: Copy Only Newer Files with Archive Mode
Command: Copy
subdir
tobackup/
, only updating newer files and preserving all attributes.# Create a new directory named backup for this example $ mkdir backup # Copy subdir to backup only if files are newer, preserving all attributes in archive mode $ cp -au subdir backup/ # List the contents of backup to verify the copy $ ls backup/
Output:
subdir
Explanation: The
-a
option preserves all attributes and copies recursively, while-u
ensures only newer files are copied. Thebackup/
directory contains an updatedsubdir
with preserved attributes.
6. Handling Special Cases
Special cases require specific handling to ensure successful copying. Below are examples with commands, outputs, and explanations.
6.1 Filenames with Spaces
Description: Filenames containing spaces must be quoted or escaped to avoid errors.
Example:
# Copy the file "file with spaces.txt" to subdir, handling the spaces in the filename with quotes $ cp "file with spaces.txt" subdir/ # List the contents of subdir to verify the file was copied $ ls subdir/
Output:
empty_file fileA.txt file with spaces.txt fileB.log sub_file.txt
Explanation: Quoting
"file with spaces.txt"
ensures the filename is treated as a single argument. The file is copied tosubdir/
without issues.
6.2 Access Control Lists (ACLs)
Description: Files with ACLs (indicated by a
+
inls -l
, e.g.,-rw-rw-r--+
) require special handling to preserve extended permissions.Example:
# Set an ACL on fileA.txt granting read permission to a user named guest $ setfacl -m u:guest:r fileA.txt # List details of fileA.txt to show the ACL (indicated by a +) $ ls -l fileA.txt # Copy fileA.txt to fileA_acl_copy.txt preserving all attributes including ACLs $ cp -a fileA.txt fileA_acl_copy.txt # Display the ACL of fileA_acl_copy.txt to verify it was preserved $ getfacl fileA_acl_copy.txt
Output:
-rw-r--r--+ 1 user user 16 May 4 18:54 fileA.txt # file: fileA_acl_copy.txt # owner: user # group: user user::rw- user:guest:r-- group::r-- mask::r-- other::r--
Explanation: The
-a
option preserves ACLs, sofileA_acl_copy.txt
retains the same ACLs asfileA.txt
, as confirmed bygetfacl
.
6.3 Copying to a Read-Only Filesystem
- Description: Copying to a read-only filesystem will fail unless handled appropriately (e.g., using
sudo
or changing permissions). - Example (assuming
/mnt/readonly
is read-only):
Output:# Attempt to copy fileA.txt to a read-only filesystem at /mnt/readonly $ cp fileA.txt /mnt/readonly/
Explanation: The command fails due to the read-only filesystem. To resolve, mount the filesystem as writable or use a different destination.cp: cannot create regular file '/mnt/readonly/fileA.txt': Read-only file system
7. Advanced/Other Options (Brief Mention)
- SELinux/SMACK Context (-Z, —context): Sets security contexts for the destination file, useful in SELinux environments.
8. Frequently Asked Questions (FAQ)
8.1 How do I copy an entire directory?
To copy an entire directory, including all its contents, use the -r
(recursive) option to copy subdirectories and files, or the -a
(archive) option to preserve attributes like permissions, timestamps, and symbolic links. The -a
option is ideal for backups as it ensures an exact replica.
- Example:
# Copy source_dir and all its contents to destination_dir preserving all attributes $ cp -a source_dir destination_dir
- Explanation: This command copies
source_dir
and all its contents todestination_dir
, preserving all file attributes.
8.2 How do I preserve permissions and timestamps when copying files?
Use the -p
option to preserve mode, ownership, and timestamps for individual files. For directories, use -a
to preserve all attributes, including symbolic links and ACLs. Root privileges may be needed to preserve ownership.
Example:
# Copy file.txt to backup preserving its mode, ownership, and timestamps $ cp -p file.txt backup/ # Copy source_dir to backup_dir preserving all attributes including directory structure $ cp -a source_dir backup_dir
Explanation: The first command copies
file.txt
tobackup/
, keeping its permissions and timestamps. The second command copiessource_dir
tobackup_dir
, preserving all attributes.
8.3 How can I avoid overwriting existing files?
Use -i
to prompt before overwriting, -n
to skip overwriting without prompting, or -u
to copy only when the source is newer than the destination or the destination is missing.
Example:
# Copy source_file to destination with a prompt before overwriting $ cp -i source_file destination # Copy source_file to destination without overwriting if the destination exists $ cp -n source_file destination # Copy source_file to destination only if source is newer or destination is missing $ cp -u source_file destination
Explanation:
-i
asks for confirmation before overwriting,-n
prevents overwriting, and-u
copies only ifsource_file
is newer.
cp -r
and cp -a
?
8.4 What’s the difference between The -r
option copies directories recursively, while -a
(archive mode) includes -r
and preserves all attributes, such as permissions, timestamps, and symbolic links. Use -a
for exact duplicates, especially for backups.
Example:
# Copy source_dir to dest_dir recursively $ cp -r source_dir dest_dir # Copy source_dir to dest_dir recursively preserving all attributes $ cp -a source_dir dest_dir
Explanation: Both commands copy
source_dir
todest_dir
, but-a
ensures all attributes are preserved.
8.5 How do I copy hidden files?
Hidden files (starting with a dot) are included by default when copying directories with -r
or -a
. For wildcard patterns, enable dotfile globbing with shopt -s dotglob
in Bash.
Example:
# Copy source_dir to dest_dir recursively including hidden files $ cp -r source_dir dest_dir # Enable globbing to include hidden files in wildcard patterns $ shopt -s dotglob # Copy all files from source_dir to dest_dir including hidden ones using wildcard $ cp source_dir/* dest_dir/ # Disable globbing after use to revert to default behavior $ shopt -u dotglob
Explanation: The first command copies all files, including hidden ones, from
source_dir
todest_dir
. The second enables dotfile globbing to include hidden files with wildcards.
8.6 What happens if SOURCE and DEST are the same file?
If the source and destination are the same file, cp
detects this and reports an error to prevent data loss.
- Example:
# Attempt to copy file.txt to itself $ cp file.txt file.txt
- Output:
cp: 'file.txt' and 'file.txt' are the same file
- Explanation: The command fails to avoid overwriting the file with itself.
8.7 How do I copy only newer files?
Use the -u
(update) option to copy files only if the source is newer than the destination or if the destination does not exist.
Example:
# Copy source_file to dest_file only if source is newer or dest_file is missing $ cp -u source_file dest_file # Copy all files from source_dir to dest_dir only if they are newer $ cp -u source_dir/* dest_dir/
Explanation: The first command copies
source_file
todest_file
only if it’s newer. The second copies newer files fromsource_dir
todest_dir
.
cp
?
8.8 How do I handle symbolic links with By default, cp
copies symbolic links as links (-P
). Use -L
to copy the target file instead. For directories, -a
preserves links during recursive copying.
Example:
# Copy the symbolic link link_to_file to dest without dereferencing it $ cp -P link_to_file dest/ # Copy the target file that link_to_file points to into dest $ cp -L link_to_file dest/ # Copy source_dir to dest_dir preserving symbolic links and all attributes $ cp -a source_dir dest_dir
Explanation:
-P
copies the link,-L
copies the target, and-a
preserves links in directories.
8.9 Can I copy files across different filesystems?
Yes, cp
can copy files across filesystems, but some attributes like hard links or extended attributes may not be preserved. For large transfers, rsync
may be more efficient.
- Example:
# Copy file.txt from source to a different filesystem mounted at /mnt/other_fs $ cp /source/file.txt /mnt/other_fs/
- Explanation: Copies
file.txt
to a different filesystem at/mnt/other_fs/
.
cp file1 file2 file3 dest
fail if dest
is not a directory?
8.10 Why does When multiple source files are specified, dest
must be a directory. If dest
is a file, cp
fails because it cannot copy multiple files into a single file.
- Example:
# Attempt to copy multiple files file1.txt, file2.txt, and file3.txt to dest_file $ cp file1.txt file2.txt file3.txt dest_file
- Output:
cp: target 'dest_file' is not a directory
- Explanation: The command fails as
dest_file
is not a directory.
cp
copy hidden files in directories?
8.11 Does Yes, hidden files are copied by default when using -r
or -a
for directories.
- Example:
# Copy source_dir to dest_dir recursively including hidden files $ cp -r source_dir dest_dir
- Explanation: All files, including hidden ones, are copied from
source_dir
todest_dir
.
cp
hang or take a long time?
8.12 Why does cp
may hang due to slow devices, large files, permission issues, or full filesystems. Check disk space, permissions, and device performance.
- Example:
# Copy a large file large_file.txt to dest which may take time depending on size and device $ cp large_file.txt dest/
- Explanation: Copying large files to slow devices can cause delays.
8.13 How do I prompt before overwriting during recursive copying?
Use -i
with -r
to prompt before overwriting files during recursive copying.
- Example:
# Copy source_dir to dest_dir recursively with a prompt before overwriting any files $ cp -ri source_dir dest_dir
- Explanation: Prompts for confirmation before overwriting any file in
dest_dir
.
8.14 How do I preserve symbolic links in directories?
Use -a
to preserve symbolic links and other attributes during directory copying.
- Example:
# Copy source_dir to dest_dir preserving symbolic links and all attributes $ cp -a source_dir dest_dir
- Explanation: Copies
source_dir
todest_dir
, preserving symbolic links.
cp
and rsync
?
8.15 What’s the difference between cp
is a simple local copying tool, while rsync
supports advanced features like delta transfers, remote copying, and synchronization, making it better for backups.
- Example:
# Synchronize source_dir with dest_dir transferring only differences with verbose output $ rsync -av source_dir dest_dir
- Explanation: Synchronizes
source_dir
withdest_dir
, transferring only differences.
8.16 How do I copy a directory structure without files?
cp
does not directly support this. Use find
to create the directory structure without files.
- Example:
# Find all directories in source_dir and recreate them in dest_dir without copying files $ find source_dir -type d -exec mkdir -p dest_dir/{} ;
- Explanation: Creates all directories from
source_dir
indest_dir
without copying files.
cp
fail with “No space left on device”?
8.17 Why does This error occurs when the filesystem is full or inodes are exhausted. Check disk space and inodes with df
.
Example:
# Check available disk space in human-readable format $ df -h # Check available inodes to see if the filesystem has run out $ df -i
Explanation:
df -h
checks disk space, anddf -i
checks inode usage. Clean up files or increase inodes if needed.
9. Conclusion
The cp
command is a powerful tool for file and directory management in Linux. Its basic functionality is simple, but options like -r
, -a
, -p
, -i
, -u
, and those for symbolic links (-L
, -P
, -d
) provide fine-grained control. By understanding these options and considering permissions and overwrite risks, users can perform efficient and safe copying operations. For detailed information, consult the man page for cp.
cp
Command: Reference Table of Key Options
10. (Copy files and directories)
Option(s) | Description | Example Command | Use Case |
---|---|---|---|
-r , -R , --recursive | Copy directories recursively | cp -r source_dir/ dest_dir/ | Copy an entire directory tree |
-p | Preserve mode, ownership, and timestamps | cp -p file.txt backup/ | Keep original metadata when copying |
-a , --archive | Archive mode (-dR --preserve=all ), best for directory copies | cp -a source_dir/ backup/ | Accurately duplicate directories preserving almost everything |
-v , --verbose | Explain what is being done | cp -v file.txt copy.txt | See confirmation for each file copied |
-i , --interactive | Prompt before overwriting an existing destination file | cp -i important.cfg backup/ | Prevent accidental overwrites |
-n , --no-clobber | Do not overwrite an existing file | cp -n update.zip deployment/ | Ensure existing destination files are untouched |
-u , --update | Copy only when source is newer or destination is missing | cp -u src/*.c build/ | Refresh files in a destination with newer source versions |
-l , --link | Create hard links instead of copying file data | cp -l data.db data_link.db | Save space by pointing multiple names to the same data |
-s , --symbolic-link | Create symbolic links instead of copying | cp -s /opt/app/run main_run | Create a shortcut to the original file |
-L , --dereference | Always follow symbolic Links in SOURCE (copy target) | cp -L link_to_data data_copy | Copy the file the symlink points to, not the link itself |
-P , --no-dereference | Never follow symbolic links in SOURCE (copy link itself) (Default) | cp -P link_to_data data_link | Copy the symlink file itself (default behavior) |
-d | Preserve links (same as --no-dereference --preserve=links ) | cp -rd source_dir/ dest/ | Ensure symlinks are copied as links during recursive copy |
-t DIR , --target-directory=DIR | Copy all SOURCE arguments into specified DIRECTORY | cp -t images/ *.jpg *.png | Specify destination directory first when copying many files |
--parents | Append source path parents to destination directory | cp --parents src/mod/f.txt bk/ | Recreate source directory structure in the destination |
-f , --force | If dest file cannot be opened, remove it and try again | cp -f source.txt dest.txt | Force copy even if destination is problematic (use carefully) |
-b , --backup[=CONTROL] | Create a backup of overwritten files | cp -b config.cfg backup/ | Keep a copy of the original file before overwriting |
-S SUFFIX , --suffix=SUFFIX | Specify a custom backup Suffix (used with -b ) | cp -bS .bak file.txt dir/ | Use a specific suffix (e.g., .bak ) for backups |