Gamora
Gamora

Reputation: 347

How can I populate an Array to use in a nested loop with filenames from a subfolder?

I don't use bash very much so bare with me!

I have this while loop that is searching for a certain file name in each folder(myFile.yaml) and then doing a load of stuff. Part of that stuff needs to also involve files (varying number) within a subfolder. I currently have it set up as a for loop that will cycle an array:

files=(thisFile.yaml thatfile.yaml otherfile.yaml)
    for file in files do;
        echo "$folder"/"morefiles"/"$value"
    done


>repo/folder1/morefiles/thisFile.yaml
>repo/folder1/morefiles/thatFile.yaml
>repo/folder1/morefiles/otherFile.yaml
>repo/folder1/morefiles/foo.yaml
> etc.

This is working as expected but now I need a way to populate files with the actual files from the subfolder.

The main folder where myFile.yaml sits has the PATH $folder so the files are within "$folder"/"moreFiles". I'm happy for files to either contain the full path and name or just the filename.

Structure:

Repo > Folder1 > myFile.yaml 
Repo > Folder1 > moreFiles > thisFile.yaml 
Repo > Folder1 > moreFiles > thatfile.yaml 
Repo > Folder1 > moreFiles > otherfile.yaml

Repo > Folder2 > myFile.yaml 
Repo > Folder2 > moreFiles > foo.yaml
Repo > Folder2 > moreFiles > barr.yaml 
Repo > Folder2 > moreFiles > foobar.yaml

Upvotes: 0

Views: 93

Answers (1)

KamilCuk
KamilCuk

Reputation: 141235

Just use the glob.

shopt -s nullglob  # just to protect
files=("$folder"/morefiles/*)

But if there's no point in storing files, then prefer not to. Just iterate over them.

for i in "$folder"/morefiles/* ; do

And you can get the same newline-separated output of files with:

printf "%s\n" "$folder"/morefiles/*

Upvotes: 4

Related Questions