Monday, March 1, 2010

Linux cp Command

 
One of my favorite commands under
Linux is the cp command. In
it's most primitive form, you use
it to copy a file like this:

cp strawberry raspberry

With the cp command, you
don't make extra work
for yourself
. Instead
of recreating a file, you
copy it.

In the above example, I copied
strawberry to raspberry.
After I've done this, I should have
two identical files.

Note that the copy command is not
limited to files. Here's how you
copy a directory and all its
contents:

cp -R banana apple

In the above example, banana
is the original directory. The
new directory is apple.

Copy always goes in this direction:

cp old new

You always copy left to right. Another
way of saying this is that you always
copy an old file to a new file, the
old file being on the left, the new
file being on the right.

Back to cp -R. Here's the example
I gave above:

cp -R banana apple

In this example, I recursively copy
a directory called banana into a new
directory called apple. I started
with banana but I ended up with both
banana and apple.

Note that it is not just the directory that
is copied. It is also all the contents of
the directory, including other files and
directories to any level of depth.

If you are used to using the term folder,
think of a directory as a folder. Folders
and directories are the same thing.

I use the term directory because the
cp command is used on the command line.
On the command line, folders are directories.

Here's one more example of the cp command:

cp -Rp pear peach

In this example, the directory pear is
being copied to the new directory called peach.
However, there is an additional nuance here. The
directory peach may be new but its timestamp
is old. That's because the -p option asks
copy to preserve both permissions and timestamps.

Had we left off the -p option, peach
would have a different timestamp. The timestamp
would be the moment peach came into existence.

Also, peach could potentially have a different
owner as well. With the -p option, ownership
defaults to the person who typed and executed the
cp command.

Again, the -p option preserves both permissions
and timestamps.

Knowing the cp command can save you
much time and energy. This is especially
true if you know the many different ways in
which it can be used.

Ed Abbott

No comments:

Post a Comment