从Shell脚本检查目录是否包含文件

时间:2020-03-06 14:20:41  来源:igfitidea点击:

从shell脚本中,如何检查目录是否包含文件?

与此类似

if [ -e /some/dir/* ]; then echo "huzzah"; fi;

但是如果目录包含一个或者多个文件(上面的一个仅适用于0或者1个文件),则该方法有效。

解决方案

尝试:

if [ ! -z `ls /some/dir/*` ]; then echo "huzzah"; fi

DIR="/some/dir"
if [ "$(ls -A $DIR)" ]; then
     echo 'There is something alive in here'
fi

你能比较一下这个输出吗?

ls -A /some/dir | wc -l

if ls /some/dir/* >/dev/null 2>&1 ; then echo "huzzah"; fi;

到目前为止的解决方案使用ls。这是一个全bash解决方案:

#!/bin/bash
shopt -s nullglob dotglob     # To include hidden files
files=(/some/dir/*)
if [ ${#files[@]} -gt 0 ]; then echo "huzzah"; fi

下列情况如何:

if find /some/dir/ -maxdepth 0 -empty | read v; then echo "Empty dir"; fi

这样就无需生成目录内容的完整列表。 read既丢弃输出,又使表达式仅在读取某些内容时才为真(即,/ find查找到/ some / dir /为空)。

注意包含大量文件的目录!评估ls命令可能需要一些时间。

IMO最好的解决方案是使用

find /some/dir/ -maxdepth 0 -empty

这可能是一个很晚的响应,但这是一个可行的解决方案。该行仅识别文件的存在!如果目录存在,它不会给我们带来误报。

if find /path/to/check/* -maxdepth 0 -type f | read
  then echo "Files Exist"
fi

# Checks whether a directory contains any nonhidden files.
#
# usage: if isempty "$HOME"; then echo "Welcome home"; fi
#
isempty() {
    for _ief in /*; do
        if [ -e "$_ief" ]; then
            return 1
        fi
    done
    return 0
}

一些实施说明:

  • for循环避免了对外部ls进程的调用。仍然会一次读取所有目录条目。这只能通过编写明确使用readdir()的C程序来进行优化。
  • 循环内的test -e捕获目录为空的情况,在这种情况下,变量'_ief'将被赋值为" somedir / *"。仅当该文件存在时,该函数才会返回"非空"
  • 此功能将在所有POSIX实现中使用。但是请注意,Solaris / bin / sh不在该类别之内。它的test实现不支持-e标志。