Tuesday, June 28, 2011

Linux Copy Command

The Linux cp (Copy) Command

I always keep forgetting the different options of the linux cp command. So I decided to make a simple list that I can reuse when need be. I have put up a few examples, it is possible to combine the different options presented. The order of the options does not matter.

Linux Straight Copy, No Options

Copy the letter.txt file on /home/myname/somedir the the destination directory: /home/yourname/somedir

$ cp /home/myname/somedir/letter.txt /home/yourname/somedir

Linux Copy a Given File to the Current Directory

Copying a file to the current directory is similar to the previous example. The current directory can be abbreviated with a single dot '.'. Thus, copying the letter.txt file on /home/myname/somedir to the current directory is done as:

$ cp /home/myname/somedir/letter.txt .

Linux Recursively Copy a Directory

The -R and -r options determine that the source directory will be copied recursively into the destination directory. Any sub-folders and or files within the source directory are copied into the destination directory.

$ cp -r /home/myname/somedir /home/yourname/myname_stuff

Linux Copy and Preserve Ownership, Mode and Timestamps

In order to preserve the ownership, mode and timestamps we need to user the -p option. The example, below copies recursively while preserving ownership, mode and timestamp.

$ cp -pr /home/myname/somedir /home/yourname/myname_stuff

Linux Make Symbolic Links Instead of Copying.

Some times we just want to make a short-cut instead of just copying the file. To achieve this we use the -s option

$ cp -s /home/myname/somedir/anotherdir/contacts/customers.txt /home/yourname/customers.txt

Linux Copy Forcefully

if an existing destination file cannot be opened, remove it and try again, -f.

$ cp -f /home/myname/somedir/letter.txt /home/yourname/letter.txt

Linux Copy Interactively

The -f option will make Linux ask you before overwriting a file.

$ cp -i /home/myname/somedir/letter.txt /home/yourname/letter.txt

No comments:

Post a Comment