atward
atward

Reputation: 3

Bash pass variable value from for loop to nested for loop

I have a nested for loop with the outer loop going through a list of directories (subject folders) that will enter into a subdirectory of each and look for a specific file. After finding that file, the directory backs up one so that the inner loop is in the proper directory to work. The inner loop then looks for specific subdirectories within the subject folder, enters those subdir, and looks for 3 specific files. The file names are assigned to variables that will then be passed to a Matlab function.

#!/usr/bin/env bash

for i in *; do #subject ID
    cd "/cygdrive/g/Data/2015_0197/$i/ASL_Data/T1_Processed" #enter into 
    specific directory
    ref_img="*smoothed*" #look for specific file1
    echo $ref_img
    cd .. #move out of directory

    for j in *ASL*; do #look for specific subdirectories
        cd "/cygdrive/g/Data/2015_0197/$i/ASL_Data/$j" #cd to each 
        subdirectory
        src_img=$i"_"$j".nii" #look for specific file2
        other_img1=$i"_"$j"_PDmap.nii" #look for specific file3
        other_img2=$i"_"$j"_ASL_fmap.nii" #look for specific file4

        echo "2nd instance---- $ref_img"
        echo $src_img
        echo $other_img1
        echo $other_img2

        #eventually call matlab function
        #matlab -nodesktop -nosplash -wait -r           
        #"coreg('$ref_img','$src_img','$other_img1','$other_img2'); exit;"
        cd ..
    done
done

At line 7, I get the correct filename for ref_img, but it does not pass into the nested for loop as line 14 will simply echo 2nd instance---- *smoothed*. How can I get it to pass that filename? I've looked into piping but due to my novice Bash knowledge, I don't know how to implement or if it's even appropriate.

Upvotes: 0

Views: 1353

Answers (1)

Jack
Jack

Reputation: 6158

The problem is that ref_img contains the wildcards, and keeps them. So when you use it, it uses those wildcards. Those files are not in the new directory. So, fix it by replacing

ref_img="*smoothed*"

with

ref_img=$( echo *smoothed* )

Upvotes: 1

Related Questions