We do love to copy…

A regular object (file, directory…) copy is a straightforward operation, it’s just a matter of replicating a object in a new location.
ie: cp /dir1/file1 /dir2/file2
Let’s start to see some theory behind it, and than apply it. Looking through the man page, there are a few options we should know when we do a cp command (they make your life a lot easier). Here are a few:

  • -d - it copies the link, it doesn’t follow it.
  • -f - doesn’t ask for confirmation to overwrite existing files
  • -i - interactively overwriting
  • -l - Creates a hard link from the source object
  • -R/-r - Recursively copies directories (copying everything “inside”)
  • -s - symlink creation to the source object
  • -u - when the source is newer than the target, or it doesn’t exist, it’s not copied

Now, shall we look into actually using the copy command? If you want to copy, let’s say, a directory to a new one, you simply do a cp dir1/ dir2/ (copy dir1 to dir2). Simple and effective, but a good guess, is that you didn’t achieve what you intended in the first place. This only copies the directory himself, not the contents.

Now if you intended was to copy everything you have inside that directory (including the directory himself), you have to do a cp -r dir1/ dir2/ (copy recursively dir1 to dir2). If the target directory does not exist, the -R/-r flag will cause dir1 to be copied in integer to dir2. Now if dir2 already exists, the situation is different; now if you type the same command, dir1 will be copied from is original source, into dir2.
If by any chance you intended to copy dir1’s contents into dir2, you have to issue the command cp dir1/* dir2/. This is because the copy command has the inability to copy things around without you to tell him to do so.

One last thing on copying… If you are sitting inside /example/dir2 and want to copy all the txt files inside /example/dir1 use the . and .. directory files. In this case you could do a cp /example/dir1/*.txt . and this would get you there! Even more fancy, you could do a cp ../dir1/*.txt . Now this is just being too geeky =)

inside dir2: mv ../dir1/*.txt .

 

LINKS: man cp



   Share This

0 comments ↓

There are no comments yet...Kick things off by filling out the form below.

Leave a Comment

Creative Commons License
dbugs.org by Marco Garcês is licensed under a Creative Commons Attribution-Noncommercial-No Derivative Works 3.0 Unported License.