Cheap Shared Hosting

Saturday, December 22, 2007

Recursively deleting folders on linux

Had this problem to resolve the other day. I had a fairly deep directory structure - and at the "end" of each path, there was one empty folder to delete. Thank you dreamweaver, but I don't need a _notes folder in every directory on my site!

So, rather than delete this manually from every directory - on both the live and staging server, I figured there had to be a way to do this in one command on linux. Of course, I had to be careful, since you can see all sorts of ways that this could go wrong with recursively deleting folders!

First, I made backups- always key when doing something like this. I just made a quick tar in my home dir, from the root of the directory I was working on:
tar -cf ~/backup.tar

Then, knowing I could fairly easily restore things that went wrong, I found the command I needed to delete the offending folders.
find . -name "_notes" -exec rm -rf {} \;

So the key here is the find command, which looks through all the directories below the current directory for files/directories called "_notes" - and then executes the command to delete the file (the -exec rm -rf part). Worked like a charm!
Also, if you want to have it ask you before deleting each file, you can add the "-i" parameter to the rm command:
find ./ -name "_notes" -exec rm -rfi {} ;
And it's only fair to point out that I figured this out from this post. Google comes through again!

No comments: