cp

Copy command in Linux is used to duplicate files or directories from one location to another within the file system. It supports copying single files, multiple files, and entire directories, with options to control overwriting and attribute preservation.

  • Copy data from one file to another
  • Copy multiple files into a directory
  • Recursively copy directories and subdirectories
  • Overwrite existing files by default

Syntax

cp [options] <source> <destination>
cp [options] <source1> <source2> <destination_directory>
--------------------------------------------------------------
cp: invokes the copy command
[options]: optional flags that modify the behavior (e.g., -i, -f, -r, -p)
<source>: the file or directory to be copied
<source1> <source2> ...: allows specifying multiple source files
<destination>: target file or directory
<destination_directory>: if copying multiple files, the destination must be a directory

Copy between two files

When the cp command is provided with two file names, it copies the contents of the source file to the destination file.

  • If the destination file does not exist, it is created.
  • If the destination file already exists, it is overwritten without warning.
cp sourece_file destination_file
cp file.txt newfile.txt
  • file.txt already exists
  • newfile.txt does not exist and will be crated with this copy command
  • content of file.txt is copied to newfile.txt

Copy files to directory

cp file1 file2 file3 group/
  • file1 file2 file3 are source files
  • group/ is destination directory
  • all 3 files are copied into group/ directory

How to copy directories

  • By default, the cp command cannot copy directories.
  • To copy a directory and its contents, the -r or -R (recursive) option must be used.
cp -R Src_directory Dest_directory
  • -R: enables recursive copying of directories
  • Src_directory: directory to be copied
  • Dest_directory: target directory
  • If Dest_directory does not exist, it is created and the contents of Src_directory are copied into it.
  • If Dest_directory already exists, Src_directory is copied as a subdirectory inside Dest_directory.

Options

  • -i : interactive mode - prompt before overwriting files
  • -f: force mode - overwrite files without prompt or warning
  • -r or -R: recursive mode - copy directories and subdirectories
  • -p: preserve attributes - retrain (if allowed) file permisions, ownerships and timestamps
    • These attributes include:
    • File permissions (read, write, execute)
    • Ownership (user and group, if you have permission)
    • Timestamps (last modification and last access times)