How to cp directory

Content on WhatAnswers is provided "as is" for informational purposes. While we strive for accuracy, we make no guarantees. Content is AI-assisted and should not be used as professional advice.

Last updated: April 4, 2026

Quick Answer: The `cp` command in Linux and macOS is used to copy files and directories. To copy a directory and its contents, use the `-r` or `-R` (recursive) option with `cp`. For example, `cp -r source_directory destination_directory` will copy the `source_directory` and everything inside it to the `destination_directory`.

Key Facts

Overview

The `cp` command is a fundamental utility in Unix-like operating systems, including Linux and macOS, used for copying files and directories. While copying a single file is straightforward (e.g., `cp file1 file2`), copying an entire directory and all its contents requires a specific option. This is because directories can contain other directories (subdirectories) and files, creating a hierarchical structure that needs to be replicated accurately.

Copying Directories with `cp -r`

To copy a directory and all its contents (files and subdirectories), you must use the recursive option, typically `-r` or `-R`. The `-r` option tells `cp` to traverse the directory structure and copy each item it encounters. Without this option, `cp` will refuse to copy a directory, usually resulting in an error message like "cp: -r not specified; omitting directory 'source_directory'".

Syntax

The basic syntax for copying a directory recursively is:

cp -r source_directory destination_directory

Behavior Scenarios

The behavior of `cp -r` depends on whether the destination directory exists:

For example, if you have a directory named project_a and you run:

cp -r project_a backups/

And the backups directory already exists, you will end up with a structure like backups/project_a/ containing all the files and subdirectories from the original project_a.

Important Considerations and Options

While `-r` is the most common option, `cp` offers other flags that can be useful:

Handling Large Directories

For very large directories or when copying over a network, `cp` might not be the most efficient tool. Utilities like `rsync` are often preferred because they can perform incremental transfers (only copying changed parts of files) and offer more advanced features for managing large-scale data synchronization.

Summary

In summary, the key to copying a directory with the `cp` command is the `-r` (recursive) flag. Combine it with other options like `-v`, `-p`, or `-a` as needed to control the copying process and preserve file attributes. Always double-check your source and destination paths to avoid accidental data loss or overwrites.

Sources

  1. Cp (Unix) - WikipediaCC-BY-SA-4.0
  2. cp(1) - Linux man pagefair-use
  3. cp - copy files and directories - Linux commandsfair-use

Missing an answer?

Suggest a question and we'll generate an answer for it.