Brian Gunter
Brian Gunter

Reputation: 83

Getting variable from inside while loop

I have a scritp that gathers information about a subdirectory of files. I am checking that the time between file creation is uniform.

last=0
LOGCHECK="YES"
ls -l /dir/*.log | gawk '{print $8}' | sed s/:/*60+/g | bc |
        while read fname
        do
            current=$fname
            if [ $last = 0 ]; then
                last=$current
            elif [ $((current - last)) -ne 1 ]; then
                echo "Time difference discrepancy: $((current - last)) minute(s) is not expected"
                LOGCHECK="NO"
                last=$current    
            else
                last=$current
            fi      
        done

This outputs only if the time between .log file creation is not one minute. My problem is that the $LOGCHECK inside the while loop is in another subshell I believe from the pipe?

Is there a way to get this variable information?

Upvotes: 1

Views: 87

Answers (1)

twalberg
twalberg

Reputation: 62379

This is a common situation with bash scripting. Restructure your loop like this:

while read fname
do
  # stuff
done < <(ls -l /dir/*.log | gawk '{print $8}' | sed s/:/*60+/g | bc)

Then variables set within the loop will still be available afterwards.

Upvotes: 3

Related Questions