Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping on empty directory content in Bash [duplicate]

Tags:

bash

loops

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?

like image 258
lerp90 Avatar asked May 05 '15 02:05

lerp90


1 Answers

You can turn on the nullglob option. It causes unmatching globs to expand to an empty list instead of being left unexpanded.

shopt -s nullglob
like image 171
Etan Reisner Avatar answered Sep 20 '22 00:09

Etan Reisner