Skip to content

The cp command in Linux: Copying files and directories

A complete guide to using the cp (copy) command in Linux: from basic copy operations to advanced techniques with attribute preservation and recursive copying.

The cp command in Linux: Copying files and directories

Introduction

While working in the terminal, you often have to copy files. The cp command (short for copy) is one of the main Linux tools for this task. It comes by default with all distributions and can copy files and folders, as well as preserve their attributes on Linux file systems.

About the cp command

The cp command is a powerful tool for copying files and directories. Its basic syntax is as follows:

bash
cp [options] <source file/directory> <target file/directory>

Basic usage examples

  1. Copying a single file:
bash
cp file.txt /home/user/documents/
  1. Copying a directory with all its contents:
bash
cp -r dir1/ dir2/

Key options of the cp command

INFO

Using the options correctly can greatly simplify the copying process and make it safer.

  1. -r or --recursive: Recursive copying of directories with all their contents
  2. -v or --verbose: Detailed output of information about the copying process
  3. -i or --interactive: Prompt for confirmation before copying files
  4. -u or --update: Copying only new or updated files
  5. -p or --preserve: Preserving all file attributes (owner, permissions, timestamps)

Advanced copying techniques

WARNING

When using advanced options, be careful, as incorrect use can lead to undesirable results.

  1. Copying with all attributes preserved:
bash
cp -ap /source/directory/* /target/directory/
  1. Copying only updated files:
bash
cp -u /source/* /destination/
  1. Copying with progress display:
bash
cp -v /source/file /target/location/

Practical recommendations

  1. Always use the -i flag when working with important files
  2. Use -r to copy directories
  3. Use -p to preserve access permissions and timestamps
  4. The -v flag will help you track the copying process
  5. Combine flags to work more efficiently

Additional information

To get detailed documentation on the cp command, you can use:

bash
man cp

INFO

It is recommended to always check access permissions and available free space before performing copy operations.

Frequently asked questions

Q: How do I copy hidden files?
A: Use the .* pattern: cp -r .* /destination/

Q: Can copying be cancelled?
A: No, the copying process cannot be cancelled once it has started. Use -i for confirmation.

INFO

Regularly make backups of important files and check the integrity of the copied data.

Our resources

Telegram channel: https://t.me/
F3 Cloud: https://f3cloud.com

F3 Cloud Knowledge Base