更新时间:2022-11-17 15:59:03
您可以检查一个目录是空的是这样的:
You can check if a directory is empty like this:
#!/bin/sh
target=$1
test "$(ls -A "$target" 2>/dev/null)" || echo The directory $target is empty
或者更好的是:
#!/bin/sh
target=$1
if test "$(ls -A "$target")"; then
echo not empty, do something
else
echo The directory $target is empty '(or non-existent)'
fi
如果该目录包含多个文件,这可以是慢。在这种情况下,这应该是较快
If the directory contains many files, this can be slow. In that case, this should be faster:
#!/bin/sh
target=$1
if find "$target" -mindepth 1 -print -quit | grep -q .; then
echo not empty, do something
else
echo The directory $target is empty '(or non-existent)'
fi
的找到
命令将打印并退出发现里面的第一个文件或目录$目标
之后。在的grep -q。
将成功退出只有当找到
打印任何东西,换句话说,如果有任何文件。
The find
command will print and quit after it finds the first file or directory inside $target
. The grep -q .
will exit with success only if the find
printed anything, in other words, if there were any files.