巴什 - 循环对空目录内容 [英] Bash - looping on empty directory content

查看:95
本文介绍了巴什 - 循环对空目录内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的,我需要遍历目录,然后遍历它们内部文件的shell脚本。所以我写了这个功能:

  loopdirfiles(){
    #LOOP了迪尔斯
    在$ {PATH}DIR / *
    做
        在$ {}目录文件/ *
            做
                回声$文件
            DONE
    DONE
}

问题是,它像回声路径* /到/ DIR / **的空目录。

的东西

有没有使用这种方法,而忽略那些种目录的方式?

在此先感谢!


解决方案

您可以剪切 * 从目录名称,而不是完全无视它:

  [$文件== **]]&放大器;&安培;文件=$ {文件/%\\ * /}
#此而来的第二循环中

或者,如果你想忽略空目录:

  [[-d $ DIR功放&;&安培; $ LS -A $ DIR)]] ||继续
#此去的第一个循环内

另一种方式:

 文件= $(禁用了javascript -s nullglob dotglob;回声$目录/ *)
(($ {#文件}))||继续
#此去的第一个循环内

或者你也可以打开 nullglob (由伊坦赖斯纳)和 dotglob :

 禁用了javascript -s nullglob dotglob
#此先行循环之前。



从猛砸手册


  

nullglob


  
  

如果设置,bash允许没有匹配文件,这些文件扩展名样式
  为空字符串,而不是自己。


  
  

dotglob


  
  

如果设置,猛砸包括一个开头的文件名。在结果
  文件名扩展。


请注意: dotglob 包括隐藏文件 在他们的名字开头的文件。) >

I'm writing a shell script in which I need to loop over directories and then loop over files inside them. So I've written this function:

loopdirfiles() {
    #loop over dirs
    for dir in "${PATH}"/*
    do
        for file in "${dir}"/*
            do
                echo $file
            done
    done
}

The problem is that it echoes something like *path/to/dir/** on empty directories.

Is there a way to use this approach and ignore those kind of directories?

Thanks in advance!

解决方案

You can cut the * from the directory name instead of completely ignoring it:

[[ $file == *"*" ]] && file="${file/%\*/}"
#this goes inside the second loop

Or if you want to ignore the empty directory:

[[ -d $dir && $ls -A $dir) ]] || continue
#this goes inside the first loop

Another way:

files=$(shopt -s nullglob dotglob; echo "$dir"/*)
(( ${#files} )) || continue
#this goes inside the first loop

Or you can turn on the nullglob (mentioned by Etan Reisner) and dotglob altogether:

shopt -s nullglob dotglob
#This goes before first loop.


From Bash Manual

nullglob

If set, Bash allows filename patterns which match no files to expand to a null string, rather than themselves.

dotglob

If set, Bash includes filenames beginning with a ‘.’ in the results of filename expansion.

Note: dotglob includes hidden files (files with a . at the beginning in their names)

这篇关于巴什 - 循环对空目录内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆