I've been trying out several methods from SU but I have been unable to do this: I got a folder (example: /var/www/tmp/) which contains several files and directories. I'd like to delete all the files and folders in this directory except for the hidden files that reside in /var/www/tmp, how can I do that?


edit: to be clear, i'd like to use this in a cronjob

2 Answers 2

find /var/www/tmp -mindepth 1 -maxdepth 1 ! -name ".*" -exec rm -r -- {} +

Will find files at maximum (and minimum) depth 1 (i.e. files directly in the given directory) that does not start with a period and execute rm -r with the matches as arguments.

Try it with a simple echo or something first to not shoot yourself in the foot before you understand exactly how it works for you.

This addresses your question about keeping all hidden files. Your topic is a bit different, but the find command is easily modified to instead just ignore files named .gitignore.

  • This doesnt work, because it also actually deletes the /var/www/tmp folder, because that is the first hit it gets
    – FLX
    Apr 18, 2012 at 15:44
  • OK, I'll add -mindepth 1. That's what happens with cowboy hacking :-) . Apr 18, 2012 at 16:15

Unless you have the shell option dotglob set, cd /var/www/tmp; rm -rf * will do what you want

  • that is great, but I intend to use it in a cronjob, my apologies for not being clear enough
    – FLX
    Apr 18, 2012 at 14:49
  • Doesn't it work when you write it in crontab? Crontab commands should be executed by sh.
    – jpalecek
    Apr 18, 2012 at 14:55
  • nope, it doesn't. Plus I consider a huge risk if it's not able to find the directory and it starts deleting stuff from the folder it started in. However, it's possible to change this by using && instead of ; to chain commands.
    – FLX
    Apr 18, 2012 at 16:17
  • With regards to your concern about not finding the folder you might try rm -rf /var/www/tmp/* Dec 30, 2013 at 21:08

You must log in to answer this question.

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