红联Linux门户
Linux帮助

Shell脚本递归删除空文件夹

发布时间:2015-02-16 15:03:19来源:linux网站作者:lurenjiashuo

有时我们需要递归删除空文件夹,网上找了一下,没有发现比较好的Shell脚本,于是自己动手写了一个
脚本

#!/bin/bash
# author: 十年后的卢哥哥(http://www.linux.com/)
# des: delete empty directories recursive
deleteempty() {
find ${1:-.} -mindepth 1 -maxdepth 1 -type d | while read -r dir
do
if [[ -z "$(find "$dir" -mindepth 1 -type f)" ]] >/dev/null
then
echo "$dir"
rm -rf ${dir} 2>&- && echo "Empty, Deleted!" || echo "Delete error"
fi
if [ -d ${dir} ]
then
deleteempty "$dir"
fi
done
}

deleteempty

脚本的内容很简单,就是遍历目录,找出空文件夹,然后删除。
使用

假如脚本文件为dedr.sh

运行脚本:

# sh dedr.sh

结果:

我们可以看到空文件夹已经被删除了。