Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have one directory where files appear in. I want to run a script regulary that finds all files in that directory that have only one link to them, and hard link them in another directory. However, I want the directory structure in the second directory to be created to match the first.

find /srcdir/ -links 1 -exec ln {} /dstdir/ \;

Does hardlink all files, but does not create the directories I need.

If a directory contains only files that have already multiple links, that directory does not need to be created in the destination.

share|improve this question
Your question states that you have "one directory where files appear in". I take it what you mean is you have one directory with various subdirectories that files appear in? – terdon Dec 8 '12 at 14:53
Yes, indeed. Files can also appear in that directory directly, but there can also be new subdirectories where files appear in. – Tom Ribbens Dec 8 '12 at 15:32

If I have understood your question correctly and you have one directory (sourcedir) with various sub directories and the linked files can be either in /sourcedir/ or in /sourcedir/foo or /sourcedir/bar etc, then this should do what you need:

find /sourcedir/ -links 1  | sed 's/.sourcedir.//' | while read n; do \
  mkdir -p /destdir/`dirname "$n"`; ln /sourcedir/"$n" /destdir/"$n"; \

It uses dirname to get the sub directory of each file and mkdir -p to create the directory structure in the destination directory.

share|improve this answer

Since hard links are rather cheap, you might make them like : (this will make hard link of all files, and create directory's as in the source)

cp -al source dest

Then you can remove the hardlinks that are in some other location on your file system. (if double hard links are a issue) Using the slightly adapted find command you posted.

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.