Copying with cp

cp copies files and directories from one place to another.

Syntaxcp [options] source destination

cp copies a file. The first argument is the source, the second is the destination.

Copying directories

To copy a whole folder and everything inside it, add the recursive option -r.

Useful options

  • -r — copy directories and their contents.
  • -i — ask before overwriting an existing file.
  • -v — verbose: print each file as it is copied.
  • -p — preserve permissions and timestamps.

Example

Example · bash
# Copy a file, keeping the same name
cp report.txt backup.txt

# Copy a file into another directory
cp report.txt /home/alice/backups/

# Copy an entire folder recursively
cp -r projects/ projects-backup/

When to use it

  • A sysadmin runs 'cp -p /etc/nginx/nginx.conf /etc/nginx/nginx.conf.bak' to back up the config before editing it.
  • A developer uses 'cp -r ./templates ./build/' to copy an entire template directory into a build folder.
  • A backup script uses 'cp -u' to copy only files that are newer than the destination, creating an efficient incremental backup.

More examples

Copy file and directory

Shows basic file copy and the -r flag required to copy a directory and all its contents.

Example · bash
# Copy a single file
cp config.yaml config.yaml.bak

# Copy directory recursively
cp -r src/ src_backup/

Preserve metadata on copy

Uses -p to preserve file attributes so the backup retains the original modification time and permissions.

Example · bash
# -p preserves permissions, timestamps, and owner
cp -p /etc/nginx/nginx.conf /tmp/nginx.conf.bak

# Verify timestamps match
stat -c '%y %n' /etc/nginx/nginx.conf /tmp/nginx.conf.bak

Copy only newer files

Combines -r, -u, and -v to do an incremental directory sync, copying only updated files verbosely.

Example · bash
# -u skips files that are not newer than the destination
cp -ru ./dist/ /var/www/html/

# -v prints each file being copied
cp -ruv ./dist/ /var/www/html/

Discussion

  • Be the first to comment on this lesson.
Copying with cp — Linux | SoundsCode