Linux : Copy directory contents to another directory

Copying the contents of one directory into another sounds easy when you can drag and drop – but when you are faced with the command line, sometimes the simplest of things can become a headache.

For the purpose of this tutorial, let’s assume our pretend file structure is as follows:

The way Linux expands it’s wildcard, or globbing characters is different from PCRE (Per Compatible Regular Expressions). Every directory in a Linux file system contains a hard link to itself under the name of “dot” (.) It also contains a hard link to its parent, called “dot dot” (..)

It is important to understand how you can and should use these links when carrying out basic file management in Linux, as they can save a lot of time.

In this exercise we will be copying the contents of /old into /new – Depending what flavour of *nix you are running, you could use the following commands and options:

but most distributions understand the simple cp -a option to mean the same thing – i.e. copy everything including symlinks. So that’s easy then, we just issue the command:

Job done! Well, yes, but what if the new directory already exist? If it did, then you would have just created a copy of old inside new. The way to ensure what you are copying goes inside the destination is by adding a trailing slash to the destination old/

The classic mistake is then to try:

This won’t work either because it will not match files that begin with a dot so you end up losing your .htaccess file:

The answer is to simply use the dot . as follows:

Don’t forget, the -a option is already recursive, so there is no need to start messing about with asterisks.

This command says copy (cp), recursively (-a) from old/. (the present directory . from within old) to new

Just remember that this dot actually represents the directory entry’s own hard link and NOT the regex dot metacharacter (which means match anything).


One Response to Linux : Copy directory contents to another directory

  1. Jay S August 22, 2014 at 12:15 #

    Superb! thanks

Leave a Reply

Time limit is exhausted. Please reload CAPTCHA.