bash 如何在 Shell Scripting 中检查目录是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36245235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check whether a directory is empty or not in Shell Scripting?
提问by Animesh
I have a directory. It is empty. If i perform ls -lrt , it shows total 0
我有一个目录。它是空的。如果我执行 ls -lrt ,它显示总数为 0
How do I specify an If condition to perform something, only if the directory is empty.
如何指定 If 条件来执行某些操作,仅当目录为空时。
I mean to ask how to capture that 0 value.
我的意思是问如何捕获那个 0 值。
回答by saan
From here. This should help you run your statements within the if else loop. I saved the DIR in the variable
从这里开始。这应该可以帮助您在 if else 循环中运行您的语句。我将 DIR 保存在变量中
#!/bin/bash
FILE=""
DIR="/empty_dir"
# init
# look for empty dir
if [ "$(ls -A $DIR)" ]; then
echo "Take action $DIR is not Empty"
else
echo "$DIR is Empty"
fi
# rest of the logic
回答by whogiawho
Remove the -A
option :
删除-A
选项:
$ mkdir /tmp/aaa
$ ls /tmp/aaa
$ a=\`ls /tmp/aaa`
$ [[ -z $a ]]
$ echo $?
0