Bash命令查看dir中是否有文件

Bash命令查看dir中是否有文件

本文介绍了Bash命令查看dir中是否有文件-测试目录是否为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下bash脚本:

I have the following bash script:

if ls /Users/david/Desktop/empty > /dev/null
then
    echo 'yes -- files'
else
    echo 'no -- files'
fi

如果/Users/david/Desktop/empty 目录中有一个或多个文件,我将如何修改顶行,使其评估为true?

How would I modify the top line such that it evaluates true if there are one or more files in the /Users/david/Desktop/empty dir?

推荐答案

.值得注意的是,为此目的使用 ls 的.

This is covered in detail in . Notably, .

shopt -s dotglob   # if including hidden files is desired
files=( "$dir"/* )
[[ -e $files || -L $files ]] && echo "Directory is not empty"

[[[-e $ files]] 实际上并不检查整个数组的内容是否存在;相反,它会检查返回的名字-处理没有文件匹配的情况,其中将glob表达式本身作为唯一结果返回.

[[ -e $files ]] doesn't actually check if the entire array's contents exist; rather, it checks the first name returned -- which handles the case when no files match, wherein the glob expression itself is returned as the sole result.

值得注意的是:

  • 与调用 ls 相比,此速度快得多,后者需要使用 fork()生成子外壳 execve()将该子Shell替换为/bin/ls ,这是操作系统的动态链接器,用于加载 ls 二进制文件等使用的共享库,等等.这是一个非常大的目录,包含成千上万个文件-在这种情况下, ls 也会很慢;请参见下面基于 find 的解决方案].
  • 与调用 ls 相比,这是更正确的:保证通过遍历返回的文件列表与文件的文字名称完全匹配,而 ls 可以用隐藏的字符来修饰名称.如果第一个条目是有效的文件名,则可以安全地迭代"$ {files [@]}" ,并确保每个返回值都是一个名称,而无需担心带有如果本地 ls 实现无法使它们转义,则其名称中的文字换行符会增加计数.
  • This is far faster than invoking ls, which requires using fork() to spawn a subshell, execve() to replace that subshell with /bin/ls, the operating system's dynamic linker to load shared libraries used by the ls binary, etc, etc. [An exception to this is extremely large directories, of tens of thousands of files -- a case in which ls will also be slow; see the find-based solution below for those].
  • This is more correct than invoking ls: The list of files returned by globbing is guaranteed to exactly match the literal names of files, whereas ls can munge names with hidden characters. If the first entry is a valid filename, "${files[@]}" can be safely iterated over with assurance that each returned value will be a name, and there's no need to worry about filesystems with literal newlines in their names inflating the count if the local ls implementation does not escape them.

也就是说,如果您使用的扩展名是 -empty (可以从GNU find和现代BSD(包括Mac OS)获得,则可以使用 find .):

That said, an alternative approach is to use find, if you have one with the -empty extension (available both from GNU find and from modern BSDs including Mac OS):

[[ $(find -H "$dir" -maxdepth 0 -type d -empty) ]] || echo "Directory is not empty"

...如果给出 any 结果,则该目录为非空目录.尽管比不大的目录慢一些,但比不存在Direntry高速缓存中的超大目录的 ls 或Globing要快,因为它可以返回结果无需全面扫描.

...if any result is given, the directory is nonempty. While slower than globbing on directories which are not unusually large, this is faster than either ls or globbing for extremely large directories not present in the direntry cache, as it can return results without a full scan.

这篇关于Bash命令查看dir中是否有文件-测试目录是否为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:26