Copy a Directory from Command Line

By  on  

Copying a directory for the sake of backup is something I do often, especially when I'm trying to figure out why something isn't working when I use an external library.  I'll copy the directory structure as a backup, mess around with the original source until I find a solution, then restore the original and change my overall system code to bring in my revised version.

You can't just use cp to copy a directory structure -- you'll see cp: myDir is a directory (not copied).  You'll need to add a few additional flags to copy a directory structure:

cp -Rp source source_copy

The above command copies the directory recursively while keeping the same permissions!

Recent Features

  • By
    Create a CSS Cube

    CSS cubes really showcase what CSS has become over the years, evolving from simple color and dimension directives to a language capable of creating deep, creative visuals.  Add animation and you've got something really neat.  Unfortunately each CSS cube tutorial I've read is a bit...

  • By
    Serving Fonts from CDN

    For maximum performance, we all know we must put our assets on CDN (another domain).  Along with those assets are custom web fonts.  Unfortunately custom web fonts via CDN (or any cross-domain font request) don't work in Firefox or Internet Explorer (correctly so, by spec) though...

Incredible Demos

  • By
    Page Visibility API

    One event that's always been lacking within the document is a signal for when the user is looking at a given tab, or another tab. When does the user switch off our site to look at something else? When do they come back?

  • By
    AJAX For Evil:  Spyjax with jQuery

    Last year I wrote a popular post titled AJAX For Evil: Spyjax when I described a technique called "Spyjax": Spyjax, as I know it, is taking information from the user's computer for your own use — specifically their browsing habits. By using CSS and JavaScript, I...

Discussion

  1. Why do you have the -s flag in there? Looking at the --help for cp, that’s the option to “make symbolic links instead of copying”, and according to Stack Overflow http://stackoverflow.com/questions/1240636 , that doesn’t even work recursively (with the -R flag). (Nor can I see why you would want to copy an entire directory recursively only for it to be populated with symlinks, especially “for the sake of backup”.) Typo?

    • EDIT: David has since corrected the error in question.

  2. Another great option that I somehow always forget to use is -a (archive), used like so:

    cp -a source source_copy

    It copies structure and permissions and also preserves symlinks.

  3. Just use rsync, faster and more options. )

  4. Good to know. But I agree with @John

  5. I prefer to use rsync for this purpose

    rsync -rav ./source/ ./destination/

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!