Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

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

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!

share|improve this question
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? – 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
up vote 3 down vote accepted

In bash:

shopt -s dotglob extglob
rm !(.htaccess)
share|improve this answer
Thanks! Is the options dotglob and extglob permanently set thereafter or are they just temporary? Am I supposed to disable them after this? – 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

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .