| Lesson 3 | Copying directories |
| Objective | Use the cp -r command to copy directories. |
A project is usually more than one file. Documents, images, configuration files, and subdirectories belong together, and copying them individually can leave an incomplete working copy. Recursive copying lets you copy a directory tree while retaining its organization. The important decisions are where the source begins, whether the destination already exists, and what should happen when destination files have matching names.
This lesson explains cp -r, familiar on GNU/Linux, and the portable recursive spelling cp -R. Both request recursion on GNU systems. Historical UNIX implementations can differ in their handling of symbolic links and special files, so do not assume that every detail of lowercase and uppercase options is interchangeable everywhere. The core examples use ordinary directories and regular files.
Copying leaves the source in place. It differs from moving or renaming an entry. Before copying, use pwd to check your current directory and use the listing techniques from the previous lesson to inspect the relevant paths. A relative path is interpreted from that working directory; an absolute path begins at the filesystem root.
cp file1.html file2.html
cp file1.html public_html
These are separate examples. In the first, assume file1.html exists and file2.html is a file destination rather than a directory. The command creates or replaces the destination file. In the second, assume public_html is an existing directory. The resulting path is public_html/file1.html. The destination type changes how the final argument is interpreted.
When copying several sources, the last operand must identify a destination directory. Syntax descriptions such as cp source... destination-directory use placeholders; the dots mean that more sources may be supplied. They are not literal filename characters to type.
Suppose images contains image files and nested directories, and project is an existing directory outside images. An ordinary copy does not descend into the source tree:
cp images project
Without a recursive option, this does not copy the directory as intended. A system might report that images is a directory or that a recursive option was not specified. Exact diagnostics vary; the important point is that copying a directory requires an option that requests traversal.
cp -r images project
On GNU/Linux this copies images and its descendants into project/images. The portable spelling for the same basic operation is:
cp -R images project
These commands are alternatives, not two steps to execute in sequence. Recursion follows the directory structure, copying entries at successive levels. It includes hidden names encountered inside the source directory without requiring a wildcard. Files in the original images tree remain present.
Assume my_folder exists, backup_folder does not exist, and the destination parent is writable. The following schematic tree illustrates the source:
my_folder/
notes.txt
images/
logo.png
.settings
cp -R my_folder backup_folder
The destination is created under the new name. Expected paths include backup_folder/notes.txt, backup_folder/images/logo.png, and backup_folder/.settings. There is no extra my_folder level beneath backup_folder in this scenario. These paths illustrate the result; they are not a transcript from your computer.
This form is useful for making a separate practice version of a small project. Choose a new destination outside the source tree. Copying a tree into one of its own descendants is not an appropriate introductory pattern and may be rejected. Also ensure the destination parent exists; recursive copying is not a general command for creating arbitrary missing parent paths.
Now consider an independent scenario in which backup_folder already exists as a directory. The command text is identical, but the resulting structure differs:
cp -R my_folder backup_folder
The source directory is placed inside that existing destination. You now expect backup_folder/my_folder/notes.txt and backup_folder/my_folder/images/logo.png. Inspect the destination before running the command so that this extra level is intentional.
If backup_folder/my_folder already exists, the operation can merge into it and overwrite conflicting files. It does not automatically create a dated version. Files that exist only in the destination are generally left there, so repeating a recursive copy is not the same as making an exact mirror.
This also explains a common practice-session surprise: after the first scenario creates backup_folder, repeating the same command changes the destination assumption. You may obtain another nesting level. Treat the scenarios separately instead of executing every example against the same evolving destination.
Sometimes you want the entries inside my_folder to land directly in an existing backup_folder, without adding the source directory name. Use the source path ending in /.:
cp -R my_folder/. backup_folder/
Assume backup_folder already exists as a directory. The expected paths are backup_folder/notes.txt, backup_folder/images/logo.png, and backup_folder/.settings. The dot refers to the source directory itself in this pathname form, allowing its contents to be copied into the selected destination.
Do not substitute my_folder/* and assume identical results. Under normal shell settings, that wildcard omits names beginning with a dot. It is expanded by the shell before cp receives its arguments. Recursive directory traversal includes hidden entries without depending on that expansion.
A bare trailing slash is also not a universal substitute for /. across implementations and symbolic-link situations. Keep the explicit form shown here and use ordinary directories while learning the destination rules.
cp -R "$HOME/project" "$HOME/project_bak"
In this example, assume project exists under your home directory and project_bak does not. The quoted paths allow spaces in the expanded home-directory path without splitting it into separate arguments. If project_bak already exists, the existing-directory rules apply instead.
Work under your own account in a small practice directory. A permission error is a reason to inspect the selected source and destination, not an automatic reason to add elevated privileges. You need appropriate access to read the source tree and create or update destination entries. Insufficient space can also interrupt a copy.
A destination filename may already contain work you want to keep. The interactive option requests confirmation before overwriting an existing destination file:
cp -Ri images project
Assume project exists. This requests a recursive copy into project/images and asks about conflicting destination files. The option does not ask before every new file is created. Read each prompt carefully; declining one replacement can leave a mixture of newly copied files and older destination files.
Interactive copying is not a transaction that either replaces everything or changes nothing. Similarly, a command that reports an error may already have copied part of the tree. Inspect the destination and the diagnostics before deciding whether to retry. A fresh destination is often easiest to understand when practicing.
Do not rely on a shell alias to add confirmation automatically. Write the intended option explicitly. Avoid combining force flags and multiple overwrite policies until you understand their interactions on the installed implementation.
The following options are useful on GNU systems, but they are not a promise about every UNIX cp implementation. Consult man cp on the machine where you will run them. Keep the destination-existence rules in mind for every variation.
cp -a my_folder archive_copy
GNU archive mode includes recursion and attempts to preserve supported attributes and links. It is not merely a shorter spelling of -r. Preservation depends on privileges and the destination filesystem, so ownership, extended attributes, access-control information, and other metadata cannot be guaranteed in every environment. Assume archive_copy is absent for this example.
cp -Rv my_folder verbose_copy
Verbose mode prints information about copying actions. It can help you see which paths are being processed, but it is not a progress percentage or a separate content-integrity check. Assume verbose_copy is absent here. An ordinary successful copy may produce no terminal output at all.
cp -Ru my_folder existing_destination
Assume existing_destination is a directory. For ordinary file comparisons, GNU -u copies missing destination files and normally replaces existing files when the corresponding source has a newer modification time. This is timestamp-based selection, not a comparison of file contents. Equal timestamps do not prove equal contents, and destination-only files are not removed.
Use update mode for a task that actually calls for that policy. It does not provide version history or complete synchronization. Avoid combining archive and update behavior casually, because preserving hard-link relationships can add interactions beyond this introductory explanation.
A symbolic link refers to a pathname rather than being an independent copy of its target. GNU recursive copying normally copies links as links, but historical and non-GNU behavior differs. Do not assume that -R alone specifies identical link handling on every UNIX implementation.
When the intended policy is to preserve symbolic links during a portable recursive copy, cp -RP makes that choice explicit. Link traversal options deserve separate attention when the source contains links; for the core exercises here, use ordinary directories and regular files so the destination structure remains easy to predict.
A recursive copy is also not automatically a consistent snapshot. Files can change while they are being copied. Copying a working project can be useful, but a reliable backup strategy involves additional requirements beyond the examples in this lesson.
After copying, inspect the destination at the level where you expect the source contents to appear. Check whether the source directory name should be included. Use a recursive listing for nested entries and include hidden names when checking configuration files. For example, if backup_folder was newly created in the first scenario:
ls -aRF backup_folder
This helps you check names and structure. It does not establish byte-for-byte equality, successful preservation of every attribute, or completeness when diagnostics reported failures. Keep those different kinds of verification distinct.
When the result is unexpected, begin with three questions: Was the destination already a directory? Did the command name the whole source directory or its contents with /.? Was the current working directory what you intended? For the contents-only form, remember that the actual suffix is /., not just a slash.
| Command | Assumption and result |
|---|---|
cp -R my_folder backup_folder | Destination absent: create backup_folder containing the source entries. |
cp -R my_folder backup_folder | Destination directory exists: copy beneath backup_folder/my_folder. |
cp -R my_folder/. backup_folder/ | Destination directory exists: copy source contents directly into it. |
cp -Ri images project | Project exists: copy recursively and ask before replacing conflicting files. |
The essential sequence is to identify the source, inspect the destination, request recursion, choose an overwrite policy, and check the result. The GNU cp manual provides additional implementation details. The next lesson explains how to remove directory trees with rm; no removal is required for the copying examples here.