user2242146
user2242146

Reputation: 11

Variable being reset to NULL in while loop

I have been having an issue that is making me tear my hair out. I am sure the answer is simple, but so far it has evaded me. Logically, this is what I am trying to do:

Check the the file systems for a particular type of mount
Run a command against those mounts to get a status of up/down
If the status is up, check 1000 lines of the log file for the string "slow response"
If found, set flag to 1 and exit loop
If not, set flag to 0 and get next line until finished
If the status is down set flag to 0 and move continue
echo $flag

Unfortunately this script is only returning NULLs. I find this strange because when I insert a echo $flag right after the assignment, it will echo the proper output. Somewhere in this code is being reset to NULL and I am unable to find it. Any thoughts? As additional info, I have checked to make sure that the values of $status, $i and $line show the proper output if I insert echo statements after their assignments.

#!/bin/bash
LOGDIR=/var/log/ceph/

df|grep osd|sed 's/.*\///'|while read i;do
   status=`ceph osd dump|grep -w "$i"|awk '{print $2}'`
   if [ $status == "up" ]; then
      tail -1000 $LOGDIR/ceph-$i.log|while read line;do
          if echo $line|grep -q "slow response";then
             let flag=1
             break
          else
             let flag=0
             continue
          fi
       done
elif [ $status == "down" ];then
       let flag=0
    fi
    echo $flag
done

Upvotes: 1

Views: 1168

Answers (2)

Wrikken
Wrikken

Reputation: 70540

see this for a full explanation

while read i;
  do something;
done < <(df|grep osd|sed 's/.*\///')

Upvotes: 0

Jens
Jens

Reputation: 72737

This looks like a Bash FAQ, especially E4) If I pipe the output of a command into read variable, why doesn't the output show up in $variable when the read command finishes?

Technically, pipes and loops are created in subshells, and like any program in Unix, the environment is passed down, but changes in the environment are never passed up.

Upvotes: 3

Related Questions