Cp Command - Copy Files and Directories | Online Free DevTools by Hexmos

Master the cp command for copying files and directories. Learn to create backups, handle symlinks, and use overwrite prompts with our comprehensive guide.

Cp Command Guide

Understanding the Cp Command

The cp command is a fundamental utility in Unix-like operating systems, used for copying files and directories. Mastering its various options allows for efficient file management directly from the command line.

Basic File and Directory Copying

The most common use of cp is to duplicate files or entire directory structures. For directories, the recursive option -r is essential.

# To copy a file:
cp ~/Desktop/foo.txt ~/Downloads/foo.txt

# To copy a directory:
cp -r ~/Desktop/cruise_pics/ ~/Pictures/

Interactive Overwriting and Backup Creation

To prevent accidental overwrites, the -i option prompts for confirmation before replacing an existing file. For creating simple backups, you can append a timestamp to the copied file.

# To create a copy but ask to overwrite if the destination file already exists:
cp -i ~/Desktop/foo.txt ~/Documents/foo.txt

# To create a backup file with date:
cp foo.txt{,."$(date +%Y%m%d-%H%M%S)"}

The cp command offers specific options for dealing with symbolic links and sparse files, ensuring that their nature is preserved during the copy process.

# To copy a symlink that points to a directory (and is thus soft) and not
# 'expand' the symlink (aka, preserve its nature as a symlink):
cp -P <symlink-dir> <dest-dir>

# To copy sparsely:
cp --sparse=always <src> <dest>

Further Resources