Some file copying went wrong in one of my machines and I'm wasting a ludicrous amount of space by having a copy of each folder inside of the parent with the same name, and I want to delete them all.


 \_ /mnt/test/files/foo/file1 (etc)
 |__ /mnt/test/files/foo/foo
 \_ /mnt/test/files/foo/foo/file1 (etc)
 |_ /mnt/files/foo/foo2
  \_ /mnt/files/foo/foo2/file1 (etc)
 |_ /mnt/files/foo/foo2/foo2
  \_ /mnt/files/foo/foo2/foo2/file1 (etc)

So obviously I want to delete /mnt/files/foo/foo, /mnt/files/foo/foo2/foo2 and its contents (and so on) entirely and stop wasting space. What would be a good way to script it in bash?


If your find supports the -regex predicate, you can list the directories with:

find . -type d -regex '.*/\([^/]*\)/\1' -prune -print

to remove them, you can change -print to:

-exec rm -rf {} +

But be sure to check the list first so you don't delete any files you need.


Using non-GNU find (but still some implementation that supports -mindepth, such as find on BSD systems):

find top-dir -depth -mindepth 1 -type d -exec sh -c '
    for pathname do
        if [ -d "$subdir" ]; then
            printf "Would remove directory %s\n" "$subdir"
            # rm -rfi "$subdir"
    done' sh {} +

This would do a depth-first traversal of the directory hierarchy rooted at top-dir. For batches of found directory pathnames, a short shell script would be called. In each iteration of the loop in the short shell script, the pathname for a subdirectory within the $pathname directory that has the same name as the directory itself is constructed. If that subdirectory exists, it is reported (the deletion is currently commented out for safety).

The -depth option causes a depth-first traversal. This is usually what you want when you delete directories with find as find would otherwise potentially try to enter directories that you have already deleted.

The -mindepth 1 option ensures that the top directory is not deleted, as it would be would you use . as the start search path.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.