Server Fault is a question and answer site for system and network administrators. 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'm trying to do some cleanup similar to this question. In a UNIX OS, I want to delete the directories that aren't being symbolic linked to in a given directory.

e.g. I have a deployment script that creates a directory structure for an app like this:

current -> /opt/myapps/fooapp/1.0-201103071729/

I want to create a script that will remove the directories in that directory that aren't the "current" directory. Thanks!

share|improve this question
up vote 1 down vote accepted

This Bash snippet will find directories that have no directories linked to them. It will also find broken links.

for f in *; do (($(find -L -maxdepth 1 -samefile "$f" 2>/dev/null | wc -l) == 1)) && echo "found: $f"; done

It does not look outside the current directory or in subdirectories.

Be sure to test it thoroughly.

share|improve this answer

As the referenced question mentioned, there isn't an official way to do this. As an alternative to Dennis' option, I present the following horrible hack. Please be sure to test thoroughly as well. I'd recommend replacing the -exec portion with an ls until you're sure it works.

touch current;find . -maxdepth 1 -type d -mmin +2 -exec rm -rf {} \;

It will check the current directory only. It essentially touches the directory linked by 'current', and then removes anything with a modify time older than two minutes. If the other directories haven't been touched in a while, you can increase the timer on -mmin, so you don't accidentally nuke the directory you want. This is obviously only viable if you don't mind changing the timestamp on the current directory.

--Christopher Karel

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.