File Management  «Prev  Next»
Lesson 3 Copying directories
Objective Use cp -r command to copy directories.

Copying Directories in Unix

You should already know the following about the cp command:
cp files directory
cp -i old new

Copying and moving files

When copying files from one directory to another you need to know for certain which directory is the current working directory. Make a copy in the current directory.
cp oldfilename newfilename
For example
cp file1.html file2.html

Make a copy in a sub-directory of the current directory

cp filename dir-name
For example
cp file1.html public_html

This will make a copy of file1.html within the public_html directory (assuming the directory exists).

Command form Result
cp oldfile newfile Copy one existing file to a new name.
cp files directory Copy files to another directory.
cp -i old new Ask first before overwriting any file.

This lesson introduces the -r option, which lets you copy a directory into another directory. The general form is:
% cp -r files directory
You must use this command form if any of the specified files is a directory. Suppose you try to copy the images directory into the project directory, without using -r. Note that the following command fails:
% cp images project

cp: images: is a directory However, with the -r option, cp recursively copies (subdirectory by subdirectory) the images directory tree into the project directory:
% cp -r images project
As with any copy operation, you might overwrite the files in the destination area if the target files have the same names as what you are copying. Use the -i option to guard against this. In the next lesson, directions on how to remove a directory tree by using the rm command will be given.