如何在Shell脚本中检查目录是否为空?(复制)

时间:2021-04-15 00:38:12

This question already has an answer here:

这个问题已经有了答案:

I have a directory. It is empty. If i perform ls -lrt , it shows total 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的值。

2 个解决方案

#1


5  

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

#2


-2  

Remove the -A option :

取消-A选项:

$ mkdir /tmp/aaa
$ ls /tmp/aaa
$ a=\`ls /tmp/aaa`
$ [[ -z $a ]]
$ echo $?
0

#1


5  

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

#2


-2  

Remove the -A option :

取消-A选项:

$ mkdir /tmp/aaa
$ ls /tmp/aaa
$ a=\`ls /tmp/aaa`
$ [[ -z $a ]]
$ echo $?
0