Deleting Files and Directories Safely in Linux

I was first exposed to UNIX-based operating systems in college during the Dark Ages (around 1991). At that time if you wanted to remove files or directories you used the rm command (or rmdir). That command is very powerful and such power led to a lot of unrecoverable files and crying undergrads as there typically was no recycle bin.

Here’s a modern and much safer alternative (that can still leverage rm): the Linux find command. I’ll leave the deep discussion to your friendly neighborhood man pages but here are the highlights:

  • The find command is recursive
  • The name parameter supports wildcards, e.g. *.txt
  • Can search for multiple entity types, e.g. files, directories, etc.
  • Easily see what you’re deleting before you delete it using the same command.

EXAMPLES

Find all files named “filename” in the current directory and any sub-directories (you can omit the starting location “period” if you’re searching the current directory):

find . -name "filename" -type f

To delete these same files, append a -delete parameter. This parameter MUST be the last parameter in the command.

find . -name "filename" -type f -delete

Find all directories and sub-directories with a certain name:

find . -name "__pycache__" -type d

Delete those same directories, sub-directories and any contained files (hello, rm!):

find . -name "__pycache__" -type d -exec rm -rf {} \;

© mylevel4cache.com, 2019. Unauthorized use and/or duplication of this material without express and written permission from this site’s author and/or owner is strictly prohibited. Excerpts and links may be used, provided that full and clear credit is given to mylevel4cache.com with appropriate and specific direction to the original content.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s