General

Bash script to find empty folders recursively

I was recently tasked with determining if a folder did not have any files in it other than more empty folders.

The one exception that was made was hidden files, we can forget about these. In this case these were all .DS_Store and “.rsrc” folders

This script will output whether a folder is empty if all other folders inside of it are also empty

#!/bin/bash

if [ ! $1 ] then mydir=`/bin/pwd` else mydir=$1 fi

echo "Searching folder: " $mydir

echo "Empty folders found:" findempty() { find "${1:-.}" -mindepth 1 -maxdepth 1 -type d -not -path '*/\.*' | while read -r dir do if [[ -z "$(find "$dir" -mindepth 1 -type f -not -path '*/\.*')" ]] >/dev/null then findempty "$dir" dirlevel="${dir//[^\/]/}"; if [[ ${#dirlevel} == 1 ]] then echo "empty: $mydir${dir:1}" fi else if [[ ${#dirlevel} == 1 ]] then echo "not empty: $mydir${dir:1}" fi fi done }

findempty