Monday, December 18, 2017

How to start a never ending script at startup




I'm trying to automatically run a never ending script (so it doesn't return 0 on exit) at startup on my headless ubuntu 12.04 server with no GUI.



I have tried @reboot nohup /home/luke/netup.sh & in crontab and the script doesn't work properly although it appears to run.
I have tried update-rc.d netup.sh defaults, the script started but still didn't run properly and most of the other programs that are supposed to auto start didn't start.



The script attempts to monitor and record internet outages and contains a while-do loop. It works when logged in to the server and started manually.



Here is the script




#!/bin/bash
#
# Script to monitor internet up time

echo "Server started" `date "+%F %T"` >> /home/luke/netup.log

START=0

while [ 1 ] ; do # continuous loop


#------------------------------------------------------------------------
/bin/ping -q 8.8.8.8 -c1 1>/dev/null 2>/dev/null # ping test
PING=$?
#------------------------------------------------------------------------

if [ $PING = 0 ]; then # ping success
if [ $START -ne 0 ]; then # was down
END=$(date +%s)
TIME=$(($END - $START))
START=0

let TIME=($TIME/60) #convert seconds to minutes
echo "Failed" $FAIL_TIME "for" $TIME "minutes" >> /home/luke/netup.log

fi

else # ping failure
if [ $START -eq 0 ]; then # was up
START=$(date +%s)
FAIL_TIME=$(date "+%F %T")
fi


fi

#------------------------------------------------------------------------
if [ $PING = 0 ]; then # wait

sleep 60
else
sleep 10
fi


done


Rather than setting up a script to run constantly at startup, why not change it to run using cron? Since you are telling it to sleep for 60 seconds between runs anyway, using cron to run a script without a while loop once a minute would make more sense and be simpler to manage.



You might also be interested in the answers for this question on serverfault:



https://serverfault.com/questions/49082/can-i-run-a-cron-job-more-frequently-than-every-minute


No comments:

Post a Comment

11.10 - Can't boot from USB after installing Ubuntu

I bought a Samsung series 5 notebook and a very strange thing happened: I installed Ubuntu 11.10 from a usb pen drive but when I restarted (...