且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

bash的检查,如果文件夹中有内容

更新时间: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

更新

如果该目录包含多个文件,这可以是慢。在这种情况下,这应该是较快

UPDATE

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.