Menu
Coddy logo textTech

Copy A Directory

Part of the Fundamentals section of Coddy's Terminal journey — lesson 17 of 82.

Just like copying a file with cp, you can also copy an entire directory. However, to copy a directory and all of its contents, you must use the -r flag, which stands for recursive.

The basic format is:

cp -r source destination

For example, to copy the documents folder and name the copy documents_backup:

cp -r documents documents_backup

Both the original folder and the copy will now exist. You can verify with ls:

ls
documents
documents_backup
readme.txt

Copying a directory into another directory:

If the destination already exists as a directory, the source folder will be placed inside it:

cp -r documents projects/

This creates projects/documents with all the original contents.

Note: Without the -r flag, cp will refuse to copy a directory and show an error. Always use -r when copying folders.

challenge icon

Challenge

Beginner

Copy the documents directory to a new directory called documents_backup, then use ls to confirm both directories exist.

Hint: Use cp -r to copy a directory and all its contents. The -r flag is required when copying folders.

Cheat sheet

To copy a directory and all of its contents, use the -r flag (recursive) with cp:

cp -r source destination

Example - copying a directory:

cp -r documents documents_backup

If the destination already exists as a directory, the source folder will be placed inside it:

cp -r documents projects/

This creates projects/documents with all the original contents.

Note: The -r flag is required when copying directories. Without it, cp will show an error.

Try it yourself

Terminal
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals