Cool bash command: Delete everything in a directory recursively, except one folder

(I’m an Ubuntu newbie, although I worked in Unix long ago. I currently work only on Windows, and shell into Ubuntu when I have to, via SFTP Net Drive Free. This bash command is cool to me anyway.)

This deletes all files and directories in the current directory only, except for the .git directory:

sudo find /home/jeffy/django_files/rest_tutorial/ -maxdepth 1 -mindepth 1 -not -name .git -exec rm -rf {} \;

I actually got scared and thought this deleted the .git directory as well, but I just forgot to use the a flag with la (ls -la).

The mindepth flag is to avoid deleting the root directory itself. The -maxdepth prevents all sub-directories and files from being returned, which are redundant with the `f` flag anyway.

(Also, never use relative paths when using rm -r!)

An example that extends this to exclude multiple items:

sudo find /home/jeffy/django_files/rest_tutorial/ -maxdepth 1 -mindepth 1 -not -name .git -not -name *.sublime-project -not -name -exec rm -rf {} \;


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s