1

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
  • this might help http://stackoverflow.com/questions/124167/bash-variable-scope – clark Apr 22 '13 at 20:21
  • Thanks to everyone that responded. I knew it had to be a simple fix, but I just couldn't get it right. All of your responses were fast and helpful. Thanks so much. I believe that I need to go fix some other scripts now :) – user2242146 Apr 22 '13 at 20:48
  • What do you mean by "NULL"? That term usually refers to a C null pointer constant; I'm not aware that it has any particular meaning in the context of bash scripting. The word "NULL" doesn't appear in the bash documentation. – Keith Thompson Apr 22 '13 at 21:20
  • NULLwithout value, effect, consequence, or significance. – user2242146 Apr 24 '13 at 16:07

2 Answers2

3

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.

Jens
  • 69,818
  • 15
  • 125
  • 179
0

see this for a full explanation

while read i;
  do something;
done < <(df|grep osd|sed 's/.*\///')
Wrikken
  • 69,272
  • 8
  • 97
  • 136
  • 1
    In a nutshell, avoid a subshell -- this rhymes :-) – Jens Apr 22 '13 at 20:29
  • It did, and then I realized I substituted one subshell (the `| while`) for another `< <(command )`, so sadly I had to delete my linguistic toying :( – Wrikken Apr 22 '13 at 20:33