Search code examples
bashfindrm

find outputs result but -exec ignores it


I wrote a simple command to find folders older than a month and delete them. Here is the command :

find . -type d -mtime +31 -exec bash -c 'rm -rfv "$0"' {} \;

It works fine in most cases, but sometime, the -exec "ignores" the result. After running the command once, If I run the find without -exec, it still finds some folders older than a month which have not been removed.

I then tried with a simple echo and got no output :

$ find . -type d -mtime +31
./folder_A
./Folder_B
$ find . -type d -mtime +31 -exec bash -c 'echo  "$0"' {} \;
<No output>

I found a workround using grep but I'm wondering why the -exec ignores some results. Anyone knows ?

Here is the workaround :

find . -type d -mtime +31 | grep . --color=never | while read line ; do rm -rvf "$line" ; done

Solution

  • Your find commands seem a bit strange to me. I'd suggest changing:

    find . -type d -mtime +31 -exec bash -c 'rm -rfv "$0"' {} \;
    

    to:

    find . -type d -mtime +31 -exec rm -rfv {} \;
    

    or even better (increases performance):

    find . -type d -mtime +31 -exec rm -rfv {} +
    

    If you insist on calling Bash explicitly (although I can't think of any reason why you should as rm is not a Bash built-in), I'd suggest changing:

    find . -type d -mtime +31 -exec bash -c 'rm -rfv "$0"' {} \;
    

    to:

    find . -type d -mtime +31 -exec bash -c 'rm -rfv {}' \;
    

    Same goes for the find command containing echo.