initialize a variable only once

hi,

i have a script which needs to be run every 10 minutes.This is achieved using crontab utility,
it is checking Number of calls on a service... if number of calls are not increasing then it will stop the service else do nothing.

Now in the script, i fetch the current value in variable myval and then compare it with variable COUNT_DEPOSIT

Here is the code:-

COUNT_DEPOSIT=0
myval=$(ls -l service | grep 449 | awk -F"|" '{print $10}')

if [ "$myval" -gt "$COUNT_DEPOSIT" ]; then
     
      do nothing
   
else
     stop the service
fi
COUNT_DEPOSIT=$myval

At the end, i reinitialize the variable COUNT_DEPOSIT with the new value so that next time COUNT_DEPOSIT variable has a new value..
But problem is that COUNT_DEPOSIT is everytime initialize to value 0

I want to initialize the this variable only once and pick the new value each time.

Can anyone please help?

thanks in advance

Write the variable (value) to a file, then read the file every time the script runs.

fname=/tmp/count.deposit
if [ ! -r $fname ]; then
  COUNT_DEPOSIT=0

else
  COUNT_DEPOSIT=$(< $fname )


# at the end of the script:
echo $COUNT_DEPOSIT > $fname

This has issues - at reboot of your app or the system, the file needs to be removed. Otherwise the code will "think" it has some previous value.
try that for a start

1 Like

it is working for me.