Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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
add comment

1 Answer

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
add comment

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.