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

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".

P.S. I recently created a nerdy privacy-respecting tool called When Will I Run Out Of Money? It's available for free if you want to check it out.

This article is © Adrian Smith.
It was originally published on 24 Jul 2007
More on: Linux & UNIX | Operating Systems | Operations & Servers