How do you copy a directory?

This is one of the most basic tasks you can do.

But it’s fraught with complexity.

The obvious requirement here is I want to copy a directory exactly as it is from A to B.

So, let’s try this on the Mac (note: this will be different if you’re on Linux):

cp -r 

I had symlinks so I got:

cp: some/directory/structure: No such file or directory

Let’s check man cp.

so cp -r does not copy symlinks.

Note: I use tldr which incorrectly says:

-a

Why? ‘cos if we look at -Pwe see:

So that’s not going to work.

OK, moving on. Let’s look at -R. Seems more like it.

On a large directory this took forever though. As an alternative, let’s try:

rsync -pvzar

Hmm. Measuring the time this took on a large directory (14 G), rsync was 50% slower.

 

More notes:

Should you have a trailing slash? On the source directory? The destination directory? Both? None?

You need the trailing slash on the source directory but the destination is optional. i.e. both of these work:

cp -R source/ destination/

cp -R source/ destination

but this:

cp -R source destination

would copy source into the destination directory.

and

cp -R source/* destination

would not copy dot files to destination.

 

A trailing / at the end of a pathname forces the pathname to refer to a directory.

https://unix.stackexchange.com/questions/1910/how-does-linux-handle-multiple-consecutive-path-separators-home-username

https://serverfault.com/questions/11518/recursive-cp-copies-folder-contents-instead-of-folder-on-os-x

https://www.linuxquestions.org/questions/linux-newbie-8/trailing-slash-or-not-4175535239/

https://superuser.com/questions/1016843/how-do-you-copy-directories-in-linux-in-these-situations-using-cp

https://superuser.com/questions/1016843/how-do-you-copy-directories-in-linux-in-these-situations-using-cp

 

Leave a Reply

Your email address will not be published. Required fields are marked *