For those of you that just want the straight goods, here’s how we delete everything EXCEPT the ‘backup’ directory:
find . -maxdepth 1 ! -name 'backup' ! -name '.*' | xargs rm -rf
Here’s a bit of a (simplistic) explanation:
- ‘find’ is the magic sauce here. We’re using it to recursively search through all the files (and directories) starting at ‘.’ (the current directory)
- the ‘!’ is the negation operator, which tells find that the operator that follow (-name) should actually perform a negative match (match everything that does NOT match this criteria)
- we also need to set up a negative match for ‘.’, ‘..’ etc, since find returns those files as well. Do note that one side effect here is that it won’t delete, for example, ‘.htacess’. You may need to modify this if you want to kill those ‘hidden’ files as well
- find is recursive, so even if it doesn’t attempt to delete the ‘backup’ directory, it will still traverse the ‘backup’ directory and delete all the files inside it, leaving an empty directory! To avoid this, we use -maxdepth 1 which effectively turns recursion off. We then make sure we recursively delete the files in the OTHER directories by using the -r flag on ‘rm’
- xargs is one way to ‘do’ something useful with the list of files and directories returned by find (find also has an -exec operator which will be able to do almost exactly the same thing, but I like xargs’ syntax better, personally). We pipe the output to xargs and then follow it with the command that we would want to run once per file/directory, in this case ‘rm -rf’
Have fun! And please backup your shit before trying this, cause one mis-step and you can trash a whole lotta stuff!
Read More