2024-11-23
The simplest use of cp involves copying a single file to a new location. The syntax is:
cp source_file destination_fileFor instance, to copy a file named mydocument.txt to a new file called mycopy.txt in the same directory:
cp mydocument.txt mycopy.txtIf mycopy.txt already exists, it will be overwritten without warning.
To copy a file to a different directory, specify the destination path:
cp source_file destination_directory/destination_fileExample: Copying mydocument.txt to a directory named backup:
cp mydocument.txt backup/mydocument.txtIf you omit the destination_file part, the file will be copied to the destination directory with its original name:
cp mydocument.txt backup/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.
Copying directories requires the -r (recursive) option. This option copies the directory and all its contents:
cp -r source_directory destination_directoryExample: Copying a directory named project to a directory named project_backup:
cp -r project project_backupThis creates a complete copy of the project directory within project_backup.
-pThe -p option preserves file attributes like timestamps, ownership, and permissions during the copy process:
cp -p source_file destination_fileThis is especially useful when you need to maintain the original file’s metadata.
-iThe -i (interactive) option prompts for confirmation before overwriting an existing file:
cp -i source_file destination_fileThis prevents accidental data loss.
-f (Force)To forcefully overwrite existing files without prompting, use the -f (force) option:
cp -f source_file destination_fileUse 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_symlinkcp 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.
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.