Copying the contents of one directory into another on Linux: not as easy at it looks!

By Adrian Smith24 Jul 2007300 words2 mins to read

Task: You want to copy the contents of one directory into another existing directory. On Linux.

I.e. if the source directory is "x" and the destination directory is the already-existing directory "y", if there are files "x/1" and "x/2" then files "y/1" and "y/2" should be created. If "x" is an empty directory then no files in "y" should be created.

Now, this is not as easy as it sounds.

cp -r x y

This command copies "x" into "y" meaning that the resulting files end up being "y/x/1" etc.

cp -r x/* y

This copies files like "x/1" into files "y/1" correctly, but if "x" is an empty directory, an error is presented, that the file "x/*" cannot be found.

Surely this should be easy! I even considered firstly deleting the directory y, and then copying x as y.

rm -rf y
cp -r x y

This is rather inelegant as you have to set the permissions on "y" again if they're non-standard, and it doesn't work if "y" isn't empty.

I came up with the following solution.

cd x
cp -r –parents . ../y</span><br style="font-family: courier new,monospace"

This copes the "current directory" and all children (i.e. all files) into "y", but the "–parents" option tries to create any hierarchy leading to the source into the destination. So if you copy "a/b/c" into "d" then it creates "d/a/b/c" as opposed to just "d/c" which it would normally create.

In my case the "hierarchy" is just "." so it copies e.g. "./1" into "y/./1" i.e. "y/1".

This article was written by Adrian Smith on 24 Jul 2007

Follow me: Facebook | Twitter | LinkedIn | Email

More on: Linux & UNIX | Operating Systems | Operations & Servers