Take the 2-minute tour ×
Ask Ubuntu is a question and answer site for Ubuntu users and developers. It's 100% free, no registration required.

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
share|improve this question
    
Did you try to call your script from /etc/rc.local? –  Eric Carvalho Sep 5 '12 at 16:56

1 Answer 1

up vote 0 down vote accepted

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:

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

share|improve this answer
    
That sounds like a great idea. I'll have to re-write the script and maybe put the contents of START variable into a text file and create a seperate cron job to record the server start time, but probably worth the effort. Thanks –  Luke Sep 10 '12 at 17:46
    
Yes, that does work, thanks again. –  Luke Sep 10 '12 at 19:39

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.