First script runs once everyday at 11am and notifies that everything is working fine with "success" message.
if [ $Status == "200" ]; then
echo "success"
else
echo "error"
fi
Second script runs every 30 minutes and doesn't print anything unless there's an error. Basically it keeps on checking every 30 minutes if everything's working fine and notifies me of an error only if anything is down.
if [ $Status != "200" ]; then
echo "error"
fi
Both the scripts have almost exactly the same code. But I'm using 2 different scripts because of different outputs I want at different times. So is there a way to combine both the scripts?
To be more clear, if possible, I want a single script that can send a success message everyday at 11am while also running every 30 minutes without sending that success message again and again and then only send error message if anything's down.
In crontab it's like this:
0 11 * * * /home/username/script1.sh
*/30 * * * * /home/username/script2.sh
CodePudding user response:
Make your script run every 30 minutes. On success, check if it is 11am before outputting success.
if [ $Status == "200" ]; then
if [ $(date %H%M) == "1100" ]; then
echo "success"
fi
else
echo "error"
fi
Note: This checks for exactly 11:00 am. If your script may take longer than 1 minute to reach this point, save the time somewhere at the beginning time="$(date %H%M)"
and check against it afterwards if [ "$time" == "1100" ]
.
Alternatively, if you want to keep the actual time at which to behave differently outside the script, you can introduce a parameter that is set only (or in one way) on the 11 am run, but not (or in another way) on the other runs.
This requires you to still have multiple cron jobs, but with different parameters to the same script.
0 11 * * * /home/username/script.sh yes
30 11 * * * /home/username/script.sh no
*/30 0-10,12-23 * * * /home/username/script.sh no
Within the script you need to check the parameter provided.
printsuccess="$1"
if [ $Status == "200" ]; then
if [ $printsuccess == "yes" ]; then
echo "success"
fi
else
echo "error"
fi
CodePudding user response:
Both the scripts have almost exactly the same code. But I'm using 2 different scripts because of different outputs I want at different times. So is there a way to combine both the scripts?
You should put all the complexity of getting the status code in a single script. Source this in wrapper scripts if neccesary: . ~/get-code.bash
.
Instead of wrapper scripts, I would do:
0,30 0-10,12-23 * * * ~/get-code || echo error
30 11 * * * ~/get-code || echo error
0 11 * * * if ~/get-code; then echo success; else echo error; fi
To return success or failure base on Status
, put this at the end of ~/get-code
:
if [ "$Status" = 200 ]; then
exit 0
else
exit 1
fi