Skip to main content Logo (IEC resistor symbol) logo

Quis custodiet ipsos custodes?
Home | About | All pages | RSS Feed | Gopher

Bash bits: find has a -delete flag

Published: 14-07-2019 | Author: Remy van Elst | Text only version of this article

Table of Contents

Bash Bits are small examples, tips and tutorials for the bash shell. This bash bit shows you that find has a -delete option. I recently found this out, before I would always use -exec rm {} \;. This is shorter and easier to remember.

If you like this article, consider sponsoring me by trying out a Digital Ocean VPS. With this link you'll get $100 credit for 60 days). (referral link)

All Bash Bits can be found using this link

find -delete flag

A long long time ago one of my co-workers showed me an option to find which removes all the files the find command found. Let's say I would want to remove all .txt files in a folder, I first would build the find command:

find . -type f -iname "*.txt"

If it found files, a list of them will be printed to the console. After checking the list, I would append the command to remove all found results:

find . -type f -iname "*.txt" -exec rm {} \;

That would, for every file, run the command rm filename;. This is a lot of typing and depending on the shell you might need to escape characters (like here).

Just now I was looking to remove all empty directories and found on the find manpage that it nowdays has a -delete flag. Which makes the above command easier:

find . -type f -iname "*.txt" -delete

Or in my case, to remove empty directories:

find . -type d -empty -delete

(if you omit the -type d find will also remove empty files).

The -delete flag will perform better since it doesn't have to spawn an external rm process for every file. However, the POSIX 1003.1 man page for find specifies -exec but not -delete, thus being the former a requirement for POSIX compatibility. Some embedded linux systems or UNIX systems therefore might also not have the delete flag.

The manpage has more information including a warning:

Delete files; true if removal succeeded. If the removal failed, an error message is issued. If -delete fails, find's exit status will be nonzero (when it eventually exits). Use of -delete automatically turns on the '-depth' option. Warnings: Don't forget that the find command line is evaluated as an expression, so putting -delete first will make find try to delete everything below the starting points you specified. When testing a find command line that you later intend to use with -delete, you should explicitly specify -depth in order to avoid later surprises.

Tags: bash , bash-bits , delete , exec , find , rm , shell , snippets