假设当前文件夹结构如下:
.
├── script.sh
├── test1
│ ├── 1.txt
│ └── 2.txt
└── test2
其中script.sh就是要运行的脚本,其内容如下:
for item in `ls .`; do
if [ -d $item ]; then
fileList=`ls ${item}`
if [[ -z $fileList ]]; then
echo "rm $item"
fi
fi
done
在命令行执行sh script.sh
,控制台输出rm test2
。
鉴于删除文件有风险,所以程序中只是打印出了删除语句,将删除语句复制或重定向保存,之后再在控制台输入就可删除文件了。
代码中的-d表示判断一个文件是否是目录,-z判断字符串是否为空,注意此处用的是[[这种条件判断,否则如果用的是[,当fileList为空的时候,bash执行会出错。
网友评论