Has this ever happened to you?
$ rmdir test
rmdir: test: Directory not empty
$ ls -A test
.DS_Store
Grrr. The directory is empty, except for the .DS_Store file which Mac OS X sometimes creates.
This happened to me enough times that I wished that Apple would create a version of ‘rmdir’ which would delete the .DS_Store iff it was the only file in an otherwise empty folder.
I’ve been waiting for Apple to do this for 4 years now, and finally decided that it was stupid to wait when I could fix the problem myself with a few lines of code.
Behold TJ’s rmdir function. (You’ll want to control+click that link if you want to download the file, otherwise it will just display in your browser.)
39 lines of actual code plus comments. Why so long? I tried to be extra careful, since we are talking about deleting files, after all.
The code itself is fairly simple:
- Take a bunch of arguments
- Check to see if those arguments translate to directories
- If they do, check to see if the directory is emptied by /bin/rmdir
- If /bin/rmdir fails, check to see if the only file in the folder is .DS_Store
- If yes, delete the file and re-run /bin/rmdir on the folder
- If no, just report the directory is not empty
Voilà.
This is a zsh function which ought to work in most bash-like shells. If you’d prefer a bash script it is also available. (I’d recommend renaming the script to ‘rmdir’ and just dropping it in your $PATH.
Tested on Mac OS X 10.6.2 using zsh 4.3.9.