简体   繁体   English

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

[英]Checking from shell script if a directory contains files

From a shell script, how do I check if a directory contains files?从 shell 脚本中,如何检查目录是否包含文件?

Something similar to this类似的东西

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

but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).但如果目录包含一个或多个文件(上述文件仅适用于恰好 0 或 1 个文件),则此方法有效。

Three best tricks三个最佳技巧


shopt -s nullglob dotglob; f=your/dir/*; ((${#f}))

This trick is 100% bash and invokes (spawns) a sub-shell.这个技巧是 100% bash并调用(生成)一个子 shell。 The idea is from Bruno De Fraine and improved by teambob 's comment.这个想法来自Bruno De Fraine ,并由teambob的评论改进。

files=$(shopt -s nullglob dotglob; echo your/dir/*)
if (( ${#files} ))
then
  echo "contains files"
else 
  echo "empty (or does not exist or is a file)"
fi

Note: no difference between an empty directory and a non-existing one (and even when the provided path is a file).注意:空目录和不存在的目录之间没有区别(即使提供的路径是文件)。

There is a similar alternative and more details (and more examples) on the 'official' FAQ for #bash IRC channel : #bash IRC 频道的“官方”常见问题解答中有类似的替代方法和更多详细信息(以及更多示例):

if (shopt -s nullglob dotglob; f=(*); ((${#f[@]})))
then
  echo "contains files"
else 
  echo "empty (or does not exist, or is a file)"
fi

[ -n "$(ls -A your/dir)" ]

This trick is inspired from nixCraft's article posted in 2007. Add 2>/dev/null to suppress the output error "No such file or directory" .这个技巧的灵感来自于nixCraft 在 2007 年发表的文章。添加2>/dev/null以抑制输出错误"No such file or directory"
See also Andrew Taylor 's answer (2008) and gr8can8dian 's answer (2011).另请参见Andrew Taylor的回答 (2008) 和gr8can8dian的回答 (2011)。

if [ -n "$(ls -A your/dir 2>/dev/null)" ]
then
  echo "contains files (or is a file)"
else
  echo "empty (or does not exist)"
fi

or the one-line bashism version:或单行 bashism 版本:

[[ $(ls -A your/dir) ]] && echo "contains files" || echo "empty"

Note: ls returns $?=2 when the directory does not exist.注意:当目录不存在时, ls返回$?=2 But no difference between a file and an empty directory.但是文件和空目录之间没有区别。


[ -n "$(find your/dir -prune -empty)" ]

This last trick is inspired from gravstar's answer where -maxdepth 0 is replaced by -prune and improved by phils 's comment.最后一个技巧的灵感来自gravstar 的答案,其中-maxdepth 0-prune替换并由phils的评论改进。

if [ -n "$(find your/dir -prune -empty 2>/dev/null)" ]
then
  echo "empty (directory or file)"
else
  echo "contains files (or does not exist)"
fi

a variation using -type d :使用-type d的变体:

if [ -n "$(find your/dir -prune -empty -type d 2>/dev/null)" ]
then
  echo "empty directory"
else
  echo "contains files (or does not exist or is not a directory)"
fi

Explanation:解释:

  • find -prune is similar than find -maxdepth 0 using less characters find -prunefind -maxdepth 0相似,使用更少的字符
  • find -empty prints the empty directories and files find -empty打印空目录和文件
  • find -type d prints directories only find -type d仅打印目录

Note: You could also replace [ -n "$(find your/dir -prune -empty)" ] by just the shorten version below:注意:您也可以将[ -n "$(find your/dir -prune -empty)" ]替换为以下缩短版本:

if [ `find your/dir -prune -empty 2>/dev/null` ]
then
  echo "empty (directory or file)"
else
  echo "contains files (or does not exist)"
fi

This last code works most of the cases but be aware that malicious paths could express a command...最后一段代码在大多数情况下都有效,但请注意恶意路径可能会表达命令......

The solutions so far use ls .到目前为止的解决方案使用ls Here's an all bash solution:这是一个全 bash 解决方案:

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

How about the following:以下情况如何:

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

This way there is no need for generating a complete listing of the contents of the directory.这样就不需要生成目录内容的完整列表。 The read is both to discard the output and make the expression evaluate to true only when something is read (ie /some/dir/ is found empty by find ). read既要丢弃输出,又要使表达式仅在读取某些内容时才计算为真(即/some/dir/find发现为空)。

尝试:

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

Take care with directories with a lot of files!注意有很多文件的目录! It could take a some time to evaluate the ls command.评估ls命令可能需要一些时间。

IMO the best solution is the one that uses IMO 最好的解决方案是使用

find /some/dir/ -maxdepth 0 -empty
# Works on hidden files, directories and regular files
### isEmpty()
# This function takes one parameter:
# $1 is the directory to check
# Echoes "huzzah" if the directory has files
function isEmpty(){
  if [ "$(ls -A $1)" ]; then
    echo "huzzah"
  else 
    echo "has no files"
  fi
}
DIR="/some/dir"
if [ "$(ls -A $DIR)" ]; then
     echo 'There is something alive in here'
fi

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

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

Some implementation notes:一些实现说明:

  • The for loop avoids a call to an external ls process. for循环避免了对外部ls进程的调用。 It still reads all the directory entries once.它仍然读取所有目录条目一次。 This can only be optimized away by writing a C program that uses readdir() explicitly.这只能通过编写显式使用 readdir() 的 C 程序来优化。
  • The test -e inside the loop catches the case of an empty directory, in which case the variable _ief would be assigned the value "somedir/*".循环内的test -e捕获空目录的情况,在这种情况下,变量_ief将被赋值为“somedir/*”。 Only if that file exists will the function return "nonempty"仅当该文件存在时,该函数才会返回“非空”
  • This function will work in all POSIX implementations.此功能适用于所有 POSIX 实现。 But be aware that the Solaris /bin/sh doesn't fall into that category.但请注意,Solaris /bin/sh 不属于该类别。 Its test implementation doesn't support the -e flag.它的test实现不支持-e标志。

This tells me if the directory is empty or if it's not, the number of files it contains.这告诉我目录是空的还是不是空的,它包含的文件数。

directory="/some/dir"
number_of_files=$(ls -A $directory | wc -l)

if [ "$number_of_files" == "0" ]; then
    echo "directory $directory is empty"
else
    echo "directory $directory contains $number_of_files files"
fi

This may be a really late response but here is a solution that works.这可能是一个非常晚的响应,但这是一个有效的解决方案。 This line only recognizes th existance of files!此行仅识别文件的存在! It will not give you a false positive if directories exist.如果目录存在,它不会给你一个误报。

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

ZSH ZSH

I know the question was marked for bash;我知道这个问题被标记为 bash; but, just for reference, for zsh users:但是,仅供参考,对于zsh用户:

Test for non-empty directory测试非空目录

To check if foo is non-empty:检查foo是否为非空:

$ for i in foo(NF) ; do ... ; done

where, if foo is non-empty, the code in the for block will be executed.其中,如果foo非空,则将执行for块中的代码。

Test for empty directory测试空目录

To check if foo is empty:检查foo是否为空:

$ for i in foo(N/^F) ; do ... ; done

where, if foo is empty, the code in the for block will be executed.其中,如果foo为空,则将执行for块中的代码。

Notes笔记

We did not need to quote the directory foo above, but we can do so if we need to:我们不需要引用上面的目录foo ,但如果需要,我们可以这样做:

$ for i in 'some directory!'(NF) ; do ... ; done

We can also test more than one object, even if it is not a directory:我们还可以测试多个对象,即使它不是目录:

$ mkdir X     # empty directory
$ touch f     # regular file
$ for i in X(N/^F) f(N/^F) ; do echo $i ; done  # echo empty directories
X

Anything that is not a directory will just be ignored.任何不是目录的东西都将被忽略。

Extras附加功能

Since we are globbing, we can use any glob (or brace expansion):由于我们是 glob,我们可以使用任何 glob(或大括号扩展):

$ mkdir X X1 X2 Y Y1 Y2 Z
$ touch Xf                    # create regular file
$ touch X1/f                  # directory X1 is not empty
$ touch Y1/.f                 # directory Y1 is not empty
$ ls -F                       # list all objects
X/ X1/ X2/ Xf Y/ Y1/ Y2/ Z/
$ for i in {X,Y}*(N/^F); do printf "$i "; done; echo  # print empty directories
X X2 Y Y2

We can also examine objects that are placed in an array.我们还可以检查放置在数组中的对象。 With the directories as above, for example:使用上述目录,例如:

$ ls -F                       # list all objects
X/ X1/ X2/ Xf Y/ Y1/ Y2/ Z/
$ arr=(*)                     # place objects into array "arr"
$ for i in ${^arr}(N/^F); do printf "$i "; done; echo
X X2 Y Y2 Z

Thus, we can test objects that may already be set in an array parameter.因此,我们可以测试可能已经在数组参数中设置的对象。

Note that the code in the for block is, obviously, executed on every directory in turn.请注意, for块中的代码显然是依次在每个目录上执行的。 If this is not desirable then you can simply populate an array parameter and then operate on that parameter:如果这不是可取的,那么您可以简单地填充一个数组参数,然后对该参数进行操作:

$ for i in *(NF) ; do full_directories+=($i) ; done
$ do_something $full_directories

Explanation解释

For zsh users there is the (F) glob qualifier (see man zshexpn ), which matches "full" (non-empty) directories:对于 zsh 用户,有(F) glob 限定符(参见man zshexpn ),它匹配“完整”(非空)目录:

$ mkdir X Y
$ touch Y/.f        # Y is now not empty
$ touch f           # create a regular file
$ ls -dF *          # list everything in the current directory
f X/ Y/
$ ls -dF *(F)       # will list only "full" directories
Y/

The qualifier (F) lists objects that match: is a directory AND is not empty.限定符(F)列出匹配的对象: 是目录且不为空。 So, (^F) matches: not a directory OR is empty.因此, (^F)匹配:不是目录或为空。 Thus, (^F) alone would also list regular files, for example.因此,例如,单独的(^F)也会列出常规文件。 Thus, as explained on the zshexp man page, we also need the (/) glob qualifier, which lists only directories:因此,正如zshexp手册页中所解释的,我们还需要(/) glob 限定符,它只列出目录:

$ mkdir X Y Z
$ touch X/f Y/.f    # directories X and Y now not empty
$ for i in *(/^F) ; do echo $i ; done
Z

Thus, to check if a given directory is empty, you can therefore run:因此,要检查给定目录是否为空,您可以运行:

$ mkdir X
$ for i in X(/^F) ; do echo $i ; done ; echo "finished"
X
finished

and just to be sure that a non-empty directory would not be captured:并且只是为了确保不会捕获非空目录:

$ mkdir Y
$ touch Y/.f
$ for i in Y(/^F) ; do echo $i ; done ; echo "finished"
zsh: no matches found: Y(/^F)
finished

Oops!哎呀! Since Y is not empty, zsh finds no matches for (/^F) ("directories that are empty") and thus spits out an error message saying that no matches for the glob were found.由于Y不为空,zsh 找不到(/^F)的匹配项(“为空的目录”),因此会吐出一条错误消息,指出未找到 glob 的匹配项。 We therefore need to suppress these possible error messages with the (N) glob qualifier:因此,我们需要使用(N) glob 限定符来抑制这些可能的错误消息:

$ mkdir Y
$ touch Y/.f
$ for i in Y(N/^F) ; do echo $i ; done ; echo "finished"
finished

Thus, for empty directories we need the qualifier (N/^F) , which you can read as: "don't warn me about failures, directories that are not full".因此,对于空目录,我们需要限定符(N/^F) ,您可以将其解读为:“不要警告我失败,目录未满”。

Similarly, for non-empty directories we need the qualifier (NF) , which we can likewise read as: "don't warn me about failures, full directories".同样,对于非空目录,我们需要限定符(NF) ,我们也可以将其读为:“不要警告我失败,完整目录”。

dir_is_empty() {
   [ "${1##*/}" = "*" ]
}

if dir_is_empty /some/dir/* ; then
   echo "huzzah"
fi

Assume you don't have a file named * into /any/dir/you/check , it should work on bash dash posh busybox sh and zsh but (for zsh) require unsetopt nomatch .假设您在/any/dir/you/check中没有名为*的文件,它应该适用于bash dash posh busybox shzsh但(对于 zsh)需要unsetopt nomatch

Performances should be comparable to any ls which use * (glob), I guess will be slow on directories with many nodes (my /usr/bin with 3000+ files went not that slow), will use at least memory enough to allocate all dirs/filenames (and more) as they are all passed (resolved) to the function as arguments, some shell probably have limits on number of arguments and/or length of arguments.性能应该与任何使用* (glob) 的ls相当,我猜在有很多节点的目录上会很慢(我的/usr/bin有 3000+ 个文件并没有那么慢),至少会使用足够的内存来分配所有目录/filenames (以及更多)因为它们都作为参数传递(解析)给函数,所以某些 shell 可能对参数的数量和/或参数的长度有限制。

A portable fast O(1) zero resources way to check if a directory is empty would be nice to have.检查目录是否为空的可移植快速 O(1) 零资源方法将是不错的选择。

update更新

The version above doesn't account for hidden files/dirs, in case some more test is required, like the is_empty from Rich's sh (POSIX shell) tricks :上面的版本不考虑隐藏文件/目录,以防需要更多测试,例如Rich 的 sh (POSIX shell) 技巧中的is_empty

is_empty () (
cd "$1"
set -- .[!.]* ; test -f "$1" && return 1
set -- ..?* ; test -f "$1" && return 1
set -- * ; test -f "$1" && return 1
return 0 )

But, instead, I'm thinking about something like this:但是,相反,我正在考虑这样的事情:

dir_is_empty() {
    [ "$(find "$1" -name "?*" | dd bs=$((${#1}+3)) count=1 2>/dev/null)" = "$1" ]
}

Some concern about trailing slashes differences from the argument and the find output when the dir is empty, and trailing newlines (but this should be easy to handle), sadly on my busybox sh show what is probably a bug on the find -> dd pipe with the output truncated randomically (if I used cat the output is always the same, seems to be dd with the argument count ).当 dir 为空时,一些关于尾随斜杠与参数和 find 输出的差异的担忧,以及尾随换行符(但这应该很容易处理),遗憾的是在我的busybox sh显示什么可能是find -> dd管道上的错误输出被随机截断(如果我使用cat输出总是相同的,似乎dd带有参数count )。

I am surprised the wooledge guide on empty directories hasn't been mentioned.我很惊讶没有提到空目录的羊毛指南 This guide, and all of wooledge really, is a must read for shell type questions.本指南,以及所有的wooleedge,都是shell类型问题的必读。

Of note from that page:该页面的注意事项:

Never try to parse ls output.永远不要尝试解析 ls 输出。 Even ls -A solutions can break (eg on HP-UX, if you are root, ls -A does the exact opposite of what it does if you're not root -- and no, I can't make up something that incredibly stupid).甚至 ls -A 解决方案也可能中断(例如,在 HP-UX 上,如果您是 root 用户,则 ls -A 的作用与您不是 root 用户的情况完全相反——不,我无法编造出令人难以置信的东西愚蠢的)。

In fact, one may wish to avoid the direct question altogether.事实上,人们可能希望完全避免直接的问题。 Usually people want to know whether a directory is empty because they want to do something involving the files therein, etc. Look to the larger question.通常人们想知道一个目录是否为空,因为他们想做一些涉及其中文件的事情,等等。看看更大的问题。 For example, one of these find-based examples may be an appropriate solution:例如,这些基于查找的示例之一可能是合适的解决方案:

   # Bourne
   find "$somedir" -type f -exec echo Found unexpected file {} \;
   find "$somedir" -maxdepth 0 -empty -exec echo {} is empty. \;  # GNU/BSD
   find "$somedir" -type d -empty -exec cp /my/configfile {} \;   # GNU/BSD

Most commonly, all that's really needed is something like this:最常见的是,真正需要的是这样的:

   # Bourne
   for f in ./*.mpg; do
        test -f "$f" || continue
        mympgviewer "$f"
    done

In other words, the person asking the question may have thought an explicit empty-directory test was needed to avoid an error message like mympgviewer: ./*.mpg: No such file or directory when in fact no such test is required.换句话说,提出问题的人可能认为需要进行明确的空目录测试以避免出现类似 mympgviewer: ./*.mpg: No such file or directory 而实际上不需要这样的测试的错误消息。

Small variation of Bruno's answer :布鲁诺答案的小变化:

files=$(ls -1 /some/dir| wc -l)
if [ $files -gt 0 ] 
then
    echo "Contains files"
else
    echo "Empty"
fi

It works for me这个对我有用

With some workaround I could find a simple way to find out whether there are files in a directory.通过一些解决方法,我可以找到一种简单的方法来找出目录中是否有文件。 This can extend with more with grep commands to check specifically .xml or .txt files etc. Ex : ls /some/dir | grep xml | wc -l | grep -w "0"这可以通过 grep 命令进行更多扩展,以专门检查 .xml 或 .txt 文件等。例如: ls /some/dir | grep xml | wc -l | grep -w "0" ls /some/dir | grep xml | wc -l | grep -w "0"

#!/bin/bash
if ([ $(ls /some/dir | wc -l  | grep -w "0") ])
    then
        echo 'No files'
    else
        echo 'Found files'
fi

Taking a hint (or several) from olibre's answer, I like a Bash function:从 olibre 的回答中得到一个提示(或几个),我喜欢 Bash 函数:

function isEmptyDir {
  [ -d $1 -a -n "$( find $1 -prune -empty 2>/dev/null )" ]
}

Because while it creates one subshell, it's as close to an O(1) solution as I can imagine and giving it a name makes it readable.因为虽然它创建了一个子外壳,但它与我想象的 O(1) 解决方案一样接近,并且给它一个名称使其可读。 I can then write然后我可以写

if isEmptyDir somedir
then
  echo somedir is an empty directory
else
  echo somedir does not exist, is not a dir, is unreadable, or is  not empty
fi

As for O(1) there are outlier cases: if a large directory has had all or all but the last entry deleted, "find" may have to read the whole thing to determine whether it's empty.至于 O(1) 存在异常情况:如果一个大目录已经删除了所有或所有但最后一个条目,“查找”可能必须读取整个内容以确定它是否为空。 I believe that expected performance is O(1) but worst-case is linear in the directory size.我相信预期的性能是 O(1),但最坏的情况是目录大小是线性的。 I have not measured this.我没有测量过这个。

if [[ -s somedir ]]; then
    echo "Files present"
fi

In my testing with bash 5.0.17, [[ -s somedir ]] will return true if somedir has any children.在我使用 bash 5.0.17 进行的测试中,如果somedir有任何孩子, [[ -s somedir ]]将返回 true。 The same is true of [ -s somedir ] . [ -s somedir ]也是如此。 Note that this will also return true if there are hidden files or subdirectories.请注意,如果存在隐藏文件或子目录,这也将返回 true。 It may also be filesystem-dependent.它也可能依赖于文件系统。

So far I haven't seen an answer that uses grep which I think would give a simpler answer (with not too many weird symbols!).到目前为止,我还没有看到使用 grep 的答案,我认为它会给出更简单的答案(没有太多奇怪的符号!)。 Here is how I would check if any files exist in the directory using bourne shell:以下是我如何使用 bourne shell 检查目录中是否存在任何文件:

this returns the number of files in a directory:这将返回目录中的文件数:

ls -l <directory> | egrep -c "^-"

you can fill in the directory path in where directory is written.可以在写入目录的地方填写目录路径。 The first half of the pipe ensures that the first character of output is "-" for each file.管道的前半部分确保每个文件的输出的第一个字符是“-”。 egrep then counts the number of line that start with that symbol using regular expressions. egrep 然后使用正则表达式计算以该符号开头的行数。 now all you have to do is store the number you obtain and compare it using backquotes like:现在您所要做的就是存储您获得的数字并使用反引号进行比较,例如:

 #!/bin/sh 
 fileNum=`ls -l <directory> | egrep -c "^-"`  
 if [ $fileNum == x ] 
 then  
 #do what you want to do
 fi

x is a variable of your choice. x 是您选择的变量。

Mixing prune things and last answers, I got to混合修剪的东西和最后的答案,我得

find "$some_dir" -prune -empty -type d | read && echo empty || echo "not empty"

that works for paths with spaces too也适用于带空格的路径

简单的答案bash

if [[ $(ls /some/dir/) ]]; then echo "huzzah"; fi;

I would go for find :我会去find

if [ -z "$(find $dir -maxdepth 1 -type f)" ]; then
    echo "$dir has NO files"
else
    echo "$dir has files"

This checks the output of looking for just files in the directory, without going through the subdirectories.这将检查仅在目录中查找文件的输出,而不通过子目录。 Then it checks the output using the -z option taken from man test :然后它使用来自man test-z选项检查输出:

   -z STRING
          the length of STRING is zero

See some outcomes:查看一些结果:

$ mkdir aaa
$ dir="aaa"

Empty dir:空目录:

$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

Just dirs in it:只是目录:

$ mkdir aaa/bbb
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

A file in the directory:目录中的一个文件:

$ touch aaa/myfile
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
$ rm aaa/myfile 

A file in a subdirectory:子目录中的文件:

$ touch aaa/bbb/another_file
$ [ -z "$(find aaa/ -maxdepth 1 -type f)" ] && echo "empty"
empty

In another thread How to test if a directory is empty with find i proposed this在另一个线程How to test if a directory is empty with find我提出了这个

[ "$(cd $dir;echo *)" = "*" ] && echo empty || echo non-empty

With the rationale that, $dir do exist because the question is "Checking from shell script if a directory contains files", and that * even on big dir is not that big, on my system /usr/bin/* is just 12Kb.理由是,$dir 确实存在,因为问题是“从 shell 脚本检查目录是否包含文件”,并且 * 即使在大目录上也没有那么大,在我的系统上 /usr/bin/* 只有 12Kb。

Update: Thanx @hh skladby, the fixed one.更新:感谢@hh skladby,已修复。

[ "$(cd $dir;echo .* *)" = ". .. *" ] && echo empty || echo non-empty

Without calling utils like ls , find, etc.:无需调用 ls 、 find 等工具:

POSIX safe, ie not dependent on your Bash / xyz shell / ls / etc. version: POSIX 安全,即不依赖于您的 Bash / xyz shell / ls / 等版本:

dir="/some/dir"
[ "$(echo $dir/*)x" != "$dir/*x" ] || [ "$(echo $dir/.[^.]*)x" != "$dir/.[^.]*x" ] || echo "empty dir"

The idea:想法:

  • echo * lists non-dot files echo *列出非点文件
  • echo .[^.]* lists dot files except of "." echo .[^.]*列出除“.”之外的点文件and ".."和 ”..”
  • if echo finds no matches, it returns the search expression, ie here * or .[^.]* - which both are no real strings and have to be concatenated with eg a letter to coerce a string如果echo找不到匹配项,则返回搜索表达式,即此处*.[^.]* -它们都不是真正的字符串,必须与例如字母连接以强制字符串
  • || alternates the possibilities in a short circuit : there is at least one non-dot file or dir OR at least one dot file or dir OR the directory is empty - on execution level: "if first possibility fails, try next one, if this fails, try next one";交替短路的可能性:至少有一个非点文件或目录或至少一个点文件或目录或目录为空 - 在执行级别:“如果第一种可能性失败,请尝试下一个,如果失败, 试试下一个"; here technically Bash "tries to execute" echo "empty dir" , put your action for empty dirs here (eg. exit).这里从技术上讲 Bash “尝试执行” echo "empty dir" ,将您对空目录的操作放在这里(例如退出)。

Checked with symlinks, yet to check with more exotic possible file types.使用符号链接进行检查,但尚未使用更奇特的可能文件类型进行检查。

It really feels like there should be an option to test for an empty directory.真的感觉应该有一个选项来test一个空目录。 I'll leave that editorial comment as a suggestion to the maintainers of the test command, but the counterpart exists for empty files.我将把该编辑评论作为对 test 命令维护者的建议留下,但对应的内容存在于空文件中。

In the trivial use case that brought me here, I'm not worried about looping through a huge number of files, nor am I worried about .files.在将我带到这里的微不足道的用例中,我不担心遍历大量文件,也不担心 .files。 I was hoping to find the aforementioned "missing" operand to test .我希望找到前面提到的“缺失”操作数来test C'est la guerre. C'est la guerre。

In the example below directory empty is empty, and full has files.在下面的示例中,目录 empty 是空的,而 full 有文件。

$ for f in empty/*; do test -e $f; done
$ echo $?
1
$ for f in full/*; do test -e $f; done
$ echo $?
0

Or, shorter and uglier still, but again only for relatively trivial use cases:或者,更短更丑,但同样只适用于相对微不足道的用例:

$ echo empty/*| grep \*
$ echo $?
1

$ echo full/* | grep \*
$ echo $?
0

to test a specific target directory测试特定的目标目录

if [ -d $target_dir ]; then
    ls_contents=$(ls -1 $target_dir | xargs); 
    if [ ! -z "$ls_contents" -a "$ls_contents" != "" ]; then
        echo "is not empty";
    else
        echo "is empty";
    fi;
else
    echo "directory does not exist";
fi;

Try with command find.尝试使用命令查找。 Specify the directory hardcoded or as argument.指定硬编码的目录或作为参数。 Then initiate find to search all files inside the directory.然后启动 find 搜索目录内的所有文件。 Check if return of find is null.检查 find 的返回是否为空。 Echo the data of find回显 find 的数据

#!/bin/bash

_DIR="/home/user/test/"
#_DIR=$1
_FIND=$(find $_DIR -type f )
if [ -n "$_FIND" ]
then
   echo -e "$_DIR contains files or subdirs with files \n\n "
   echo "$_FIND"
else
echo "empty (or does not exist)"
fi
if ls /some/dir/* >/dev/null 2>&1 ; then echo "huzzah"; fi;

Works well for me this (when dir exist):这对我很有效(当 dir 存在时):

some_dir="/some/dir with whitespace & other characters/"
if find "`echo "$some_dir"`" -maxdepth 0 -empty | read v; then echo "Empty dir"; fi

With full check:全面检查:

if [ -d "$some_dir" ]; then
  if find "`echo "$some_dir"`" -maxdepth 0 -empty | read v; then echo "Empty dir"; else "Dir is NOT empty" fi
fi

I dislike the ls - A solutions posted.我不喜欢ls - A解决方案。 Most likely you wish to test if the directory is empty because you don't wish to delete it.您很可能希望测试该目录是否为空,因为您不想删除它。 The following does that.以下是这样做的。 If however you just wish to log an empty file, surely deleting and recreating it is quicker then listing possibly infinite files?但是,如果您只想记录一个空文件,那么删除和重新创建它肯定比列出可能无限的文件更快吗?

This should work...这应该工作...

if !  rmdir ${target}
then
    echo "not empty"
else
    echo "empty"
    mkdir ${target}
fi

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM