在Bash中循环播放空目录内容 [英] Looping on empty directory content in Bash

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

问题描述

我正在编写一个shell脚本,其中需要循环浏览目录,然后循环浏览其中的文件.所以我写了这个函数:

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
}

问题在于它在空目录中回显* path/to/dir/**之类的东西.

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?

推荐答案

您可以从目录名称中剪切*,而不是完全忽略它:

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

另一种方式:

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

或者您可以同时打开nullglob(由 Etan Reisner 提及)和dotglob:

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

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


摘自Bash手册

nullglob

nullglob

如果设置,则Bash允许扩展没有文件匹配的文件名模式 设置为空字符串,而不是它们本身.

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

dotglob

如果已设置,则Bash在以下结果中会包含以."开头的文件名 文件名扩展.

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

注意:dotglob包含隐藏文件(文件名开头带有.的文件)

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

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

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