Need help with bash checking if computer uptime is greater than 5 minutes

I have an bash script that runs on a every minute cron. It checks to see if a necessary program is running and starts it if it is not. Occasionally it will run before the user has actually autologged in. I want to prevent that from happening.

What I think I'd like to do is to put a check in the check the computer's uptime and see if it'd been on for 5 minutes so that auto login had a chance to finish before the program gets started. I'm fairly new to bash and parsing what I get from "uptime" to where I could use it for comparison seems out of my reach.

Can anyone help? Perhaps there is a better solution. I'm stuck.


Solution 1:

A bash script/cron job is the wrong solution for the problem you are trying to solve. Actually, scratch that -- two bash scripts/cron jobs are the wrong solution for your problem. ;)

The problem you are trying to solve is, "ensure a task starts running after a user has logged in, and ensure it stays running". This is a job for upstart.

The following should do what you want, and it goes into /etc/init/. Name the file something like user-session-job.conf.

description "Keep my very important program running"

start on desktop-session-start
stop on desktop-shutdown

respawn

script
    /path/to/my/very/important/program
end script

Please see the upstart cookbook for lots more help: http://upstart.ubuntu.com/cookbook/

Solution 2:

Since I had to alter the script drastically from the original, I decided to post this as a separate answer. I'm not sure why the code above does not work. I apologise, I should have tested it before posting it. I have verified that the code below however, does in fact work.

#!/bin/bash

upSeconds="$(cat /proc/uptime | grep -o '^[0-9]\+')"
upMins=$((${upSeconds} / 60))

if [ "${upMins}" -gt "5" ]
then
    echo "Up for ${upMins} minutes"
else
    echo "Up five minutes or less"
fi

Solution 3:

This would be enough:

test $(cut -d '.' -f1 /proc/uptime) -gt 300

Script example:

if test $(cut -d '.' -f1 /proc/uptime) -gt 300; then
  echo "booted more than 5 minutes ago"
else
  echo "too early"
fi

Solution 4:

Try this

#!/bin/bash
#
#   upt - show just the system uptime, days, hours, and minutes

let upSeconds="$(cat /proc/uptime) && echo ${temp%%.*})"
let secs=$((${upSeconds}%60))
let mins=$((${upSeconds}/60%60))
let hours=$((${upSeconds}/3600%24))
let days=$((${upSeconds}/86400))
if [ "${days}" -ne "0" ]
then
   echo -n "${days}d"
fi
echo -n "${hours}h${mins}m"