Skip to content

Linux cp command examples and usage

Command definition

The cp command in Linux is used to copy files and directories from one location to another. It can operate in various modes, allowing users to copy single files, multiple files, or entire directories, with options to preserve file attributes, prompt before overwriting, and more. This command is essential for file management in the Linux environment.

Usage examples

  1. Copy a single file: This command copies a file from one location to another.
    Example: cp filename.txt /path/to/destination/

  2. Copy multiple files: This command allows you to copy several files at once to a specified directory.
    Example: cp file1.txt file2.txt /path/to/destination/

  3. Copy a directory recursively: This command copies an entire directory and its contents to a new location.
    Example: cp -r myfolder /path/to/destination/

  4. Preserve file attributes: This command copies a file while preserving its mode, ownership, and timestamps.
    Example: cp -p filename.txt /path/to/destination/

  5. Prompt before overwriting: This command will ask for confirmation before overwriting an existing file in the destination.
    Example: cp -i filename.txt /path/to/destination/

  6. Copy with verbose output: This command provides detailed information about what is being copied.
    Example: cp -v filename.txt /path/to/destination/

  7. Copy files with a specific extension: This command copies all files with a certain extension from one directory to another.
    Example: cp *.txt /path/to/destination/

  8. Copy to a different name: This command allows you to copy a file and rename it in the destination.
    Example: cp filename.txt /path/to/destination/newfile.txt

  9. Copy files while excluding certain types: This command allows for selective copying by excluding certain file types.
    Example: cp --exclude='*.log' -r myfolder /path/to/destination/

  10. Copy files and create a backup: This command creates a backup of the destination file before copying.
    Example: cp -b filename.txt /path/to/destination/