Wednesday, February 2, 2022

[SOLVED] Cooldown for a certain command in bash

Issue

I am writing a shell script (#!/bin/sh) on my RPI that sends emails whenever a sensor measures above a certain degree celsuis.

Since the sensors get triggered every minute for logging, a temperature above 30 degrees for about an hour would resolve in 60 mails, which is not what i want.

Is there a way to set a cooldown for the command that sends the mail?

Here is the code that checks the sensor data and sends mails if above 30 degrees (its solved with functions but i think thats irrelevant):

if [ $tempC -ge 40 ]
then
  #logging code
  mailSend "WARNING: Temperature is currently: $temp and Humidity is: ${file#"sensor_dhtH"}" #This command needs a cooldown
elif [ $tempC -ge 30 ]
then
  #logging code
  mailSend "Attention: Temperature is currently: $temp and Humidity is: ${file#"sensor_dhtH"}" #This command needs a cooldown
else
  #logging code
fi

Thanks in advance :)


Solution

Alright, thanks to @Mark Setchell i was able to get to this solution:

limit=$((2*60*60)) #limit is 2 hours

if [ $SECONDS -ge $limit ] #if seconds-since-last-send greater or equal to your-set-limit(here 2h)
then
#send the mail
SECONDS=0 #set the seconds-since-last-send to 0
else
echo "not yet ma man, wait some seconds" #not sending the mail cuz its too early to send another
fi

I didn't know about the $SECONDS variable that counts itself up before, so that defenetly was helpful, thanks :)



Answered By - Obama
Answer Checked By - David Marino (WPSolving Volunteer)