Quoting from the contents of an empty directory in Bash

I am writing a shell script in which I need to iterate over directories and then iterate over files inside them. So I wrote 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 the empty * path / to / dir / ** directory.

Is there a way to use this approach and ignore these types of directories?

+5
source share
2 answers

You can exclude * from the directory name and not completely ignore it:

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

Or, if you want to ignore an 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 include nullglob (mentioned by Etan Reisner ) and dotglob in general:

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


From Bash Manual

nullglob

If set, Bash resolves file name patterns that do not match files for extension to an empty string, not to itself.

dotglob

If set, Bash contains file names starting with the 'character. in the results is the file name extension.

Note: dotglob contains hidden files (files with . In the beginning in their names)

+2
source

You can enable the nullglob parameter. This causes unmatching globs to expand to an empty list instead of remaining unexpanded.

 shopt -s nullglob 
+4
source

All Articles