Ubuntu – How to copy a directory into itself

command linecpdirectory

I can copy a directory like so:

~$ cp -r ./Desktop/ /tmp/

Similarly, if I just wanted to copy the files from within a directory, I could do so:

~$ cp -r ./Desktop/. /tmp/

Things become a little more tricky if I want to copy the source directory into a target directory, that is a sub-directory of the source. i.e. copy a directory into itself. For example:

~$ cp -r ./Desktop/ ./Desktop/sub/

Would throw the following error: cp: cannot copy a directory, './Desktop/', into itself, './Desktop/sub/'

This can be circumnavigated, somewhat, using extglob, like so:

~$ cp -r ./Desktop/!(sub) ./Desktop/sub/

However, this last command is dependent on the directory sub already existing.

How can you copy a directory into itself, in such a fashion that the command to do so creates the sub directory at the same time?

Best Answer

Use rsync instead of cp:

rsync -Rr ./Desktop/ ./Desktop/sub/

Let's test it out:

$ cd /tmp
$ mkdir -p Desktop/sub
$ touch Desktop/a-file
$ ls -F Desktop
a-file sub/
$ cp ./Desktop ./Desktop/sub
cp: cannot copy a directory, './Desktop', into itself, './Desktop/sub/Desktop'

However rsync will work fine:

$ rsync -Rr ./Desktop/ ./Desktop/sub/
$ ls -F Desktop/sub/
Desktop/