Creating symbolic links in every folder of a folder structure

This article describes how to create a symbolic link in several folders in linux with just one line of code.

Tux IllustrationI had the following situation with this folder structure on a linux machine.

- /var
  | www_main
  | www_1
  | www_2
  | www_3

There were several DocumentRoots for an Apache server defined which served serveral virtual hosts. In every document root content was stored, which should be available in all virtual hosts. This is a hell of a maintenace if you have dozens of such virtual hosts and have to update the content. A solution is to work with dynamic links. The idea is that you save the content in one main  folder (here: /var/www_main) and create symbolic links in all others.
Even then you can save much time by an efficent use of the find command in linux. Just find all folders of the first directory level below /var which have a name starting with ‘www’ and create the symbolic links to the target in every returned folder.

This is achieved by

$ find /var/ -maxdepth 1 -type d -name 'www*' -exec ln -s /var/www_main/image.jpg {}/image.jpg \;

Et voila.
It is no problem that the folder ‘www_main’ is included in the result of the find command.  The original files already exist there and are therefore not overwritten.
The target of the symbolic link can be a folder or a file. If you use this approach on a webserver, make sure that your server is configured to follow symbolic links.

Take care of what you are doing – it is always a security threat to allow webserver to access files and content outside of your server’s Document Root! And this happens quite fast with symbolic links!

Of course you can take this approach and actually use it for every operation you want to execute on a folder structure.