If your definition of an empty directory tree is that it contains no files then you be able to stick something together based on whether find test -type f returns anything.
find -type d -empty -exec rmdir -vp --ignore-fail-on-non-empty {} +
在旧版本的 find中,还不支持语句 +,因此可以使用 ;:
find -type d -empty -exec rmdir -vp --ignore-fail-on-non-empty {} `;`
目录是空的吗?
Most of these answers explain how to check if a directory is empty. Therefore I provide here the three different techniques I know:
[ $(find your/dir -prune -empty) = your/dir ]
d=your/dir
if [ x$(find "$d" -prune -empty) = x"$d" ]
then
echo "empty (directory or file)"
else
echo "contains files (or does not exist)"
fi
一种变化:
d=your/dir
if [ x$(find "$d" -prune -empty -type d) = x"$d" ]
then
echo "empty directory"
else
echo "contains files (or does not exist or is not a directory)"
fi
解说:
find -prune is similar than find -maxdepth 0 using less characters
find -type d只打印目录
find -empty prints the empty directories and files
> mkdir -v empty1 empty2 not_empty
mkdir: created directory 'empty1'
mkdir: created directory 'empty2'
mkdir: created directory 'not_empty'
> touch not_empty/file
> find empty1 empty2 not_empty -prune -empty
empty1
empty2
(( ${#files} ))
This trick is 100% bash but invokes (spawns) a sub-shell. The idea is from Bruno De Fraine and improved by teambob's comment. I advice this one if you use bash and if your script does not have to be portable.
files=$(shopt -s nullglob dotglob; echo your/dir/*)
if (( ${#files} ))
then
echo "contains files"
else
echo "empty (or does not exist or is a file)"
fi