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 destinationFor example, to copy the documents folder and name the copy documents_backup:
cp -r documents documents_backupBoth the original folder and the copy will now exist. You can verify with ls:
ls
documents
documents_backup
readme.txtCopying 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
BeginnerCopy the documents directory to a new directory called documents_backup, then use ls to confirm both directories exist.
Hint: Use
cp -rto copy a directory and all its contents. The-rflag 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 destinationExample - copying a directory:
cp -r documents documents_backupIf 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
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline