Removing Directories With Find

find is a command-line utility that allows you to search for files and directories based on a given expression and perform an action on each matched file or directory.

The most common scenario is to use the find command to delete directories based on a pattern. For example, to delete all directories that end with _cache in the current working directory, you would run:

$ find . -type d -name '*_cache' -exec rm -r {} +

Let’s analyze the command above:

  • /dir – recursively search in the current working directory (.).
  • -type d – restricts the search to directories.
  • -name '*_cache' – search only directories that end with _cache
  • -exec – executes an external command with optional arguments, in this case, that is rm -r.
  • {} + – appends the found files to the end of the rm command.

Removing all empty directories

To remove all empty directories in a directory tree you would run:

$ find /dir -type d -empty -delete

Here is an explanation for the options used:

  • /dir – recursively search in the /dir directory.
  • -type d – restricts the search to directories.
  • -empty – restricts the search only to empty directories.
  • -delete – deletes all found empty directories in the subtree. -delete can delete only empty directories.

Use the -delete option with extreme caution. The find command line is evaluated as an expression, and if you add the -delete option first, the command will delete everything below the starting points you specified.

Always test the command first without the -delete option and use -delete as the last option.

/bin/rm: Argument list too long

This error message appears when you use the rm command to remove a directory that contains a huge number of files. This happens because the number of files is larger than the system limit on the size of the command line argument.

There are several different solutions to this problem. For example, you can cd to the directory and manually or using a loop to remove sub-directories one by one.

The easiest solution is first to delete all files within the directory with the find command and then delete the directory:

$ find /dir -type f -delete && rm -r /dir