0

to delete files on under folder we can use the following approach with find

find /home -type f -delete

but how to delete recursive only the files that exists under temp folder ?

lets say we have the following example of temp path

/home/bla/bla/temp
/home/test/temp
/home/subf/subf/subf/temp
.
.
.
/home/1/temp

how to change the find syntax in order to delete only the files under temp directory

the target is to use find command in order to match only the temp folders and remove the files under temp directory

King David
  • 781
  • 2
  • 14
  • 27
  • So you want to delete all files inside any directory named `temp`, *but* not the directory itself? Please confirm. `-type f` in your example matches regular files, but you keep saying "files". [This is a broad term](https://superuser.com/a/1467109/432690). Do you really mean (all) files? or regular files? Removing regular files only will leave directories, symlinks, sockets and such intact. Please [edit] the question and clarify. – Kamil Maciorowski Jul 03 '22 at 09:26
  • I answered the question according to my interpretation of it. If you clarify (see my first comment) and the answer needs to be adjusted to the new interpretation then I will adjust it. – Kamil Maciorowski Jul 03 '22 at 10:09
  • Please [do not cross-post](https://meta.stackexchange.com/a/64069/355310). For the record, the other copy is [on Unix & Linux SE](https://unix.stackexchange.com/q/708434/108618). – Kamil Maciorowski Jul 03 '22 at 15:57

1 Answers1

4

The following command will find regular files in any directory named temp and below, below /home.

find /home -type f -path '*/temp/*'

To actually delete them:

find /home -type f -path '*/temp/*' -delete

Notes:

  • By default find does not follow symlinks. See man 1 find for options -L, -H and (if supported) -P.

  • -delete is not portable. If your find does not support -delete, use -exec rm {} +. -delete is better not only because it doesn't create an additional process. It is safer as it (at least -delete implemented in GNU find) removes the race condition where someone may be able to make you remove the wrong file(s) by changing some directory to a symlink in-between the time find finds a file and rm removes it. The fact our find command does not follow symlinks is irrelevant at this point.

Kamil Maciorowski
  • 69,815
  • 22
  • 136
  • 202