All HowTo's Linux Ubuntu, Mint & Debian Linux Web Servers

How to Copy a Directory Structure While Excluding the Files | Linux

Sometimes it’s necessary to copy a directory structure without copying the actual files. This is a two step process as i’ve demonstrated below. However, i bet you can do it with a single command using “find” and its “exec” feature.

In this example we’ll copy the “/etc” directory structure.

cd /etc
find ./ -type d > /tmp/etc-structure

That created a new file called “/tmp/etc-structure” which has contents that look like the following. Notice the “-type d” in the above “find” command. That excludes files and lists only directories.

./
./sudoers.d
./sysctl.d
./update-notifier
./python2.7
./X11
./X11/xinit
./X11/xinit/xinitrc.d
./X11/Xsession.d
./X11/xkb
...

Now we use the above as a template to create the new structure. Go to where you want to create the new structure and run the following command. We’ll create ours in “/test”.

mkdir /test
for var in `cat /tmp/etc-structure`; do mkdir ${var}; done

The above command create the following structure of directories. There are sub-directories of course but i’m showing on the top level directories. I’ve listed only the first 10 directories here:

cd /test
ls -l | head
drwxr-xr-x 3 root root 4096 Nov 27 02:27 acpi
drwxr-xr-x 2 root root 4096 Nov 27 02:27 alternatives
drwxr-xr-x 3 root root 4096 Nov 27 02:27 apache2
drwxr-xr-x 3 root root 4096 Nov 27 02:27 apm
drwxr-xr-x 3 root root 4096 Nov 27 02:27 apparmor
drwxr-xr-x 9 root root 4096 Nov 27 02:27 apparmor.d
drwxr-xr-x 3 root root 4096 Nov 27 02:27 apport
drwxr-xr-x 6 root root 4096 Nov 27 02:27 apt
drwxr-xr-x 2 root root 4096 Nov 27 02:27 bash_completion.d

You’ll noticed we’ve not considered file permissions and ownership. That’s a separate problem.

Leave a Reply

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