As the question suggests, I have a situation where I have a folder that users can upload weird stuff there. Have a cron job set up to clean this folder every a few hours.

It has a .htaccess for security reasons, of course, my question is, how can I delete everything (files and directories) in that directory, including hidden ones whose name start with a dot, but not the .htaccess?

I currently have rm -rf * to do the job but if the user uploads a file with a name starting with a dot, it would not be deleted.

Any help would be much appreciated. Thanks!

  • 1
    Why don't you copy the .htaccess to a new directory, remove the whole directory at once, then rename the directory back? – Alvin Wong Dec 29 '12 at 10:28
  • Thanks for the tip. What do you mean by renaming the directory back? I thought it's removed? Wouldn't this approach temporarily disable the uploading feature? – datasn.io Dec 29 '12 at 11:08
  • he means something like mkdir newDir; cp uploadDir/.haccess newDir; rmdir uploadDir; mv newDir uploadDir; – mcalex Dec 29 '12 at 11:26
  • The method above will stop uploads for the tiny amount of time the folder doesn't exist. Ingacio's answer works and keeps the directory intact. – mcalex Dec 29 '12 at 11:33
  • It will also interfere with external tools such as SELinux that depend on certain properties of the directory itself. – Ignacio Vazquez-Abrams Dec 29 '12 at 12:48

In bash:

shopt -s dotglob extglob
rm !(.htaccess)
  • Thanks! Is the options dotglob and extglob permanently set thereafter or are they just temporary? Am I supposed to disable them after this? – datasn.io Dec 29 '12 at 11:59
  • They're set until you disable them. If you want them temporarily set then run the commands in a subshell. – Ignacio Vazquez-Abrams Dec 29 '12 at 12:32

I'd use find, like: find /path/to/dir/ -mindepth 1 -not -name .htaccess -delete

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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