Scra
Scra

Reputation: 137

Bash - How to make the loop run only once?

Whenever files in count directory changes, I need to calculate the total count and if the total count is between 50 and 100, I need to run a script with input N - which takes only 1 sec to run.

The problem is when the total count increases each time from 50 to 100, the script is executing each time. Is there a way to stop the loop/script from running the second time?

while inotifywait -r -e modify $dir
do

line=$(grep -ho '[0-9]*' /var/count* | awk '{sum+=$1} END {print sum}')

echo "********** count is $line **********"

if [ $line -ge 50 ] && [ $line -lt 100 ]
then
echo "_____________executing if 1 _______________"
export N=1
/var/test.sh
fi

if [ $line -ge 100 ] && [ $line -lt 150 ]
then
echo "_____________executing if 2 _______________"
export N=2
/var/test.sh
fi
done

Upvotes: 3

Views: 1881

Answers (1)

RTLinuxSW
RTLinuxSW

Reputation: 842

I am not sure why you have two "done" statements.

I am having a difficult time following the problem. Is this what you want? Each "if" will only execute once

export N=0
while inotifywait -r -e modify $dir
do
   line=$(grep -ho '[0-9]*' /var/count* | wc -l)
   if [ $N -lt 1 -a $line -ge 50 -a $line -lt 100 ]
   then
       export N=1
       /var/test.sh

   elif [ $N -lt 2 -a $line -ge 100 -a $line -lt 150 ]
   then
       export N=2
       /var/test.sh
   fi
done

Adjust code for the behavior you desire.

Upvotes: 2

Related Questions