【发布时间】:2011-10-14 07:16:25
【问题描述】:
我正在尝试在 unix shell 脚本中编写一个 if 语句,如果它为空则返回 true,否则返回 false。
这种东西……
if directory foo is empty then
echo empty
else
echo not empty
fi
我该怎么做?有人告诉我 find 是一个很好的起点
【问题讨论】:
我正在尝试在 unix shell 脚本中编写一个 if 语句,如果它为空则返回 true,否则返回 false。
这种东西……
if directory foo is empty then
echo empty
else
echo not empty
fi
我该怎么做?有人告诉我 find 是一个很好的起点
【问题讨论】:
简单 - 使用 -empty 标志。引用 find 手册页:
-empty True if the current file or directory is empty.
比如:
find . -type d -empty
将列出所有空目录。
【讨论】:
必须有一种更简单的方法,但是您可以使用管道将ls -1A 传输到wc -l 来测试空/非空目录
DIRCOUNT=$(ls -1A /path/to/dir |wc -l)
if [ $DIRCOUNT -eq 0 ]; then
# it's empty
fi
【讨论】:
三个最佳答案:
find OP 要求的;ls;bash,但它调用(生成)一个子 shell。[ $(find your/dir -prune -empty) = your/dir ]
dn=your/dir
if [ x$(find "$dn" -prune -empty) = x"$dn" ]; then
echo empty
else
echo not empty
fi
测试:
> 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
find 仅打印了两个空目录(empty1 和 empty2)。
这个答案看起来像来自Ariel 的-maxdepth 0 -empty。但是这个答案有点短;)
[ $(ls -A your/directory) ]
if [ "$(ls -A your/dir)" ]; then
echo not empty
else
echo empty
fi
或
[ "$(ls -A your/dir)" ] && echo not empty || echo empty
类似于Michael Berkowski 和gpojd 的答案。但是这里我们不需要通过管道传递给wc。另见Bash Shell Check Whether a Directory is Empty or NotnixCraft (2007)。
(( ${#files} ))
files=$(shopt -s nullglob dotglob; echo your/dir/*)
if (( ${#files} )); then
echo not empty
else
echo empty or does not exist
fi
注意:如上例所述,空目录和不存在的目录没有区别。
最后一个答案的灵感来自Bruno De Fraine's answer 和来自teambob 的优秀 cmets。
【讨论】:
find directoryname -maxdepth 0 -empty
【讨论】:
为什么必须使用 find?在 bash 中,ls -a 将为空目录返回两个文件(. 和 ..),并且应该比非空目录更多。
if [ $(ls -a | wc -l) -eq 2 ]; then echo "empty"; else echo "not empty"; fi
【讨论】:
. 和..。管道到 wc 时不需要 -l 标志。
if [ `find foo | wc -l` -eq 1 ]
then
echo Empty
else
echo Not empty
fi
foo是这里的目录名。
【讨论】:
如下所示
dircnt.sh:
-----------
#!/bin/sh
if [ `ls $1 2> /dev/null | wc -l` -gt 0 ]; then echo true; else echo false; fi
用法
andreas@earl ~
$ mkdir asal
andreas@earl ~
$ sh dircnt.sh asal
false
andreas@earl ~
$ touch asal/1
andreas@earl ~
$ sh dircnt.sh asal
true
【讨论】:
我不喜欢使用 ls,因为我有一些非常大的目录,我讨厌浪费资源来填充管道。
我也不喜欢用所有这些东西填充 $files 变量。
因此,虽然@libre 的所有答案都很有趣,但我发现它们都难以阅读,并且更喜欢制作我最喜欢的“查找”解决方案的功能:
function isEmptyDir {
[ -d $1 -a -n "$( find $1 -prune -empty 2>/dev/null )" ]
}
这样我就可以编写一年后可以阅读的代码,而不用问“我在想什么”?
if isEmptyDir some/directory
then
echo "some/directory is empty"
else
echo "some/directory does not exist, is not a directory, or is empty
fi
或者我可以使用其他代码来梳理负面结果,但该代码 应该很明显。无论如何,我马上就会知道我在想什么。
【讨论】:
没有脚本,没有 fork/exec(echo 是内置的)...
[ "$(cd $dir;echo *)" = "*" ] && echo empty || echo non-empty
【讨论】: