The cp (copy) command is used to copy files and directories in a Linux filesystem.
-
Syntax:
cp [options] source destination -
Examples:
cp file.txt /backup/
- Copies
file.txtto the/backup/directory.
cp file.txt newfile.txt
- Copies
file.txtand names the copynewfile.txt.
cp -r /documents /backup/
- Recursively copies the
/documents/directory and its contents to/backup/.
cp -i file.txt /backup/
- Prompts for confirmation before overwriting any existing files in
/backup/.
cp -v file.txt /backup/
- Verbosely shows what is being copied.
- Copies
-
-ror--recursive:- Recursively copies directories and their contents.
cp -r folder /backup/
- Copies the
folderdirectory and all its contents to/backup/.
-
-ior--interactive:- Prompts before overwriting files.
cp -i file.txt /backup/
- Asks for confirmation before overwriting
file.txtin/backup/.
-
-for--force:- Forces overwriting of existing files without prompting.
cp -f file.txt /backup/
- Overwrites
file.txtin/backup/without confirmation.
-
-vor--verbose:- Displays what is being copied.
cp -v file.txt /backup/
- Shows that
file.txtis being copied to/backup/.
-
-uor--update:- Copies only when the source file is newer than the destination file or when the destination file is missing.
cp -u file.txt /backup/
- Updates
file.txtin/backup/only if it is newer than the existing file.
-
-aor--archive:- Copies files and directories, including attributes like permissions and timestamps, as well as symbolic links.
cp -a /documents /backup/
- Creates an exact copy of
/documents/in/backup/.
-
--help:- Displays help information about the
cpcommand.
cp --help
- Shows usage information and options.
- Displays help information about the
-
Be Mindful of Overwrites:
- Without options like
-i,cpwill overwrite files in the destination without warning. Use-ito prompt before overwriting.
- Without options like
-
Copying Multiple Files:
- To copy multiple files to a directory, list the files followed by the destination directory.
cp file1.txt file2.txt /backup/
-
Wildcard Usage:
- Use wildcards to copy multiple files that match a pattern.
cp *.txt /backup/- Copies all
.txtfiles to the/backup/directory.
The cp command is essential for copying files and directories in Linux. It supports various options to control how files are copied, including recursive copying, prompting before overwrites, and preserving file attributes. Use it carefully, especially when overwriting files.