cp

2024-11-23

Basic File Copying

The simplest use of cp involves copying a single file to a new location. The syntax is:

cp source_file destination_file

For instance, to copy a file named mydocument.txt to a new file called mycopy.txt in the same directory:

cp mydocument.txt mycopy.txt

If mycopy.txt already exists, it will be overwritten without warning.

Copying to a Different Directory

To copy a file to a different directory, specify the destination path:

cp source_file destination_directory/destination_file

Example: Copying mydocument.txt to a directory named backup:

cp mydocument.txt backup/mydocument.txt

If you omit the destination_file part, the file will be copied to the destination directory with its original name:

cp mydocument.txt backup/

Copying Multiple Files

cp can efficiently handle multiple files at once. You can list them individually or use wildcards:

cp file1.txt file2.txt file3.txt destination_directory/

Using wildcards:

cp *.txt backup/

This copies all files ending in .txt to the backup directory.

Recursive Copying of Directories

Copying directories requires the -r (recursive) option. This option copies the directory and all its contents:

cp -r source_directory destination_directory

Example: Copying a directory named project to a directory named project_backup:

cp -r project project_backup

This creates a complete copy of the project directory within project_backup.

Preserving Attributes with -p

The -p option preserves file attributes like timestamps, ownership, and permissions during the copy process:

cp -p source_file destination_file

This is especially useful when you need to maintain the original file’s metadata.

Interactive Copying with -i

The -i (interactive) option prompts for confirmation before overwriting an existing file:

cp -i source_file destination_file

This prevents accidental data loss.

Overwriting with -f (Force)

To forcefully overwrite existing files without prompting, use the -f (force) option:

cp -f source_file destination_file

Use caution with this option!

By default, cp copies the contents of a symbolic link, not the link itself. To copy the symbolic link itself, use the -s option:

cp -s source_symlink destination_symlink

Understanding Errors

cp will typically return an error code if a file cannot be copied (e.g., due to permission issues). Check the return code using $? after running the cp command. A non-zero value indicates an error.

Advanced Usage and Options

The cp command offers additional options for finer control over the copy process. Refer to the man cp page for a complete list and detailed descriptions of all available options. Experimenting with these options will improve your proficiency with this Linux command.