How do I create a copy of a directory in Unix/Linux?
To copy an entire directory (including all subdirectories and files) on Unix/Linux, you typically use cp -r
(recursive copy). Here’s a simple example:
cp -r /path/to/source_directory /path/to/destination_directory
Key Options
-r
(or-R
): Recursively copies all subdirectories and files.-p
: Preserves file attributes (timestamps, ownership, permissions).cp -rp /path/to/source /path/to/destination
Example Usage
# Basic recursive copy cp -r my_folder backup_my_folder # Recursive copy preserving timestamps, ownership, and permissions cp -rp my_folder backup_my_folder
Tip: If the destination folder doesn’t exist yet, cp
will create it. If it does exist, the source directory will be copied inside the destination directory. Check that your paths align with what you intend to achieve.
Alternative Approaches
1. Using rsync
rsync
is often used for more advanced copying, offering progress information, partial transfers, and other powerful features. For a simple local copy:
rsync -av my_folder/ backup_my_folder/
-a
: Archive mode (recursively copy and preserve attributes).-v
: Verbose output.- A trailing slash (e.g.
my_folder/
) ensures you copy contents intobackup_my_folder/
.
2. Using tar
for Very Large Directories
You can compress and copy huge directories by first creating a tarball, then extracting it elsewhere (potentially on another machine). For local copying, you can even pipe between two tar
commands:
# Create a tarball tar -czf my_folder.tar.gz my_folder # Extract it tar -xzf my_folder.tar.gz -C /new/location
Or, in a single step (if you need to copy from one place to another on the same system):
cd /old/location tar cf - my_folder | (cd /new/location && tar xf -)
This technique is useful if you need to preserve symlinks, extended attributes, or have extremely large directory trees.
Further Learning
Beyond directory management, mastering Unix/Linux tools and honing your coding fundamentals can significantly boost your productivity. Check out these two courses from DesignGurus.io:
-
Grokking Data Structures & Algorithms for Coding Interviews
Develop a solid grasp of key data structures and algorithmic strategies—critical for building efficient, reliable software. -
Grokking the Coding Interview: Patterns for Coding Questions
Learn the most common patterns behind coding interview challenges and elevate your problem-solving abilities.
With robust Unix command-line skills combined with strong algorithmic knowledge, you’ll be well-prepared to tackle both system-level tasks and high-level software engineering challenges.