Overview
The cp (copy) command is a fundamental tool used for duplicating files and directories. Beyond simple duplication, it is capable of complex operations such as creating system backups that preserve permissions and timestamps, or creating symbolic links to save disk space. It is one of the most frequently used commands in server construction and maintenance, particularly when backing up configuration files before editing.
Specifications (Arguments and Options)
Syntax
# Copy a file to a new name
cp [options] [source_file] [destination_file]
# Copy multiple files into a directory
cp [options] [source_file...] [destination_directory]
Main Options
The cp command offers a wide range of options for backup and link management.
| Option | Description |
-a | Archive mode. Copies recursively and preserves file attributes (owner, permissions, timestamps) and structure. Ideal for backups. |
-i | Interactive mode. Prompts for confirmation before overwriting an existing file. |
-r, -R | Recursive. Copies directories and their contents. |
-u | Update. Copies only if the destination file does not exist or if the source is newer than the destination. |
-p | Preserves file owner, group, permissions, and timestamps. |
-s | Creates symbolic links instead of copying data. |
-l | Creates hard links instead of copying data. |
-t [dir] | Target directory. Explicitly specifies the destination directory, useful when combined with xargs. |
-b | Backup. Creates a backup of overwritten files (appends ~ to the name). |
-S [suffix] | Specifies a custom suffix for backup files. |
-L | Always follows symbolic links in source and copies the actual file. |
-P | Never follows symbolic links; copies the link itself. (Included in -a). |
Basic Usage
Duplicating a File
The simplest use case is copying a file to a new name.
cp production.conf production.conf.bak
Execution Result Example:
(No output is shown if successful, but the file is duplicated.)
ls -l production.conf*
-rw-r--r-- 1 user group 1024 Jan 15 10:00 production.conf
-rw-r--r-- 1 user group 1024 Jan 16 09:00 production.conf.bak
Practical Commands
1. Copying Directories while Preserving Permissions (-a)
When backing up web server document roots or configuration directories, changing the owner or permissions can cause services to fail. Using the -a option ensures these attributes are perfectly maintained.
# Completely copy /var/www/html to /var/www/html_backup
sudo cp -a /var/www/html /var/www/html_backup
Execution Result Example:
ls -l /var/www/
drwxr-xr-x 2 www-data www-data 4096 Jan 01 00:00 html
drwxr-xr-x 2 www-data www-data 4096 Jan 01 00:00 html_backup
Note that the timestamps and the owner (www-data) are preserved.
2. Creating Symbolic Links to Save Space (-s)
If you need to place large data files in another location without consuming additional disk space, use the -s option to create a “shortcut.”
# Create a symbolic link named link_to_data for big_data.iso
cp -s /mnt/storage/big_data.iso ./link_to_data
Execution Result Example:
ls -l link_to_data
lrwxrwxrwx 1 user group 24 Jan 16 09:10 link_to_data -> /mnt/storage/big_data.iso
3. Copying Massive Amounts of Files (xargs + -t)
Attempting to copy tens of thousands of files using cp *.log dir/ often results in an “Argument list too long” error. To circumvent this, use find or ls results with a pipe to xargs and the -t option.
# Copy all .log files in the current directory to ../log_archive/
find . -maxdepth 1 -name "*.log" -print0 | xargs -0 cp -t ../log_archive/
Using find -print0 and xargs -0 ensures that filenames containing spaces are handled safely.
Customization Points
- Overwrite Confirmation (
-i): Many environments havealias cp='cp -i'set by default. When writing scripts, explicitly use-f(force) or-n(no-clobber) to ensure deterministic behavior. - Updating Only Changed Files (
-u): Useful for syncing large directories by only copying files that have been modified. (For professional synchronization, thersynccommand is recommended). - Backup Suffix (
-S): Runningcp -b -S .old target.txt dest/will preserve the overwritten file astarget.txt.old.
Important Notes
- Forgetting
-rfor Directories: If you attempt to copy a directory without-r(or-a), you will receive an “omitting directory” error, and no files will be copied. - Attribute Preservation and Root Privileges: If a regular user tries to use
-aor-pto copy system files owned by root, the preservation of ownership may fail (Permission denied). Usesudoin these cases. - Symlink Handling: By default, copying a link may copy the “target entity” instead of the link itself. Use
-Por-d(included in-a) to copy the link as a link.
Advanced Application
Creating Numbered Backups
Before editing a configuration file, you can move the existing file into a numbered backup format such as config.conf.~1~.
# If config.conf exists, rename it to config.conf.~1~ and create a new copy
cp --backup=t config.conf /etc/app/config.conf
Conclusion
The cp command is a pillar of Linux operations. Utilizing the correct options significantly increases safety.
Reminder: Always use -r for directories and combine sudo with -a to maintain permissions.The -a (Archive) option is the most robust choice for backups as it replicates the source state as closely as possible.
Best Use Cases: File duplication, pre-edit backups, and full directory archiving.
Key Adjustments: Use -a for perfect backups, -s for space-saving links, and -t with xargs for large-scale operations.
