What's the best way to tell from a shell script if the host has restarted since the last time the script was run? I can think of storing the uptime in a file on each run, and checking if it has decreased, but that doesn't seem completely robust (a server might restart start quickly, store a low uptime, then reboot slowly and come up with a higher uptime).
Is there something like a "started at" value which would be guaranteed to change only on a reboot? Or some other good way of detecting a restart?
If you don't want to use cron, you could also create a directory in
/dev/shm
. Since that location is in memory, it will always be empty when the computer starts up. If it's not empty, you haven't rebooted.Use the
@reboot
directive in /etc/crontab to create the directory when the system starts.sar
command will help you in this.http://linux.die.net/man/1/sar
Another approach would be to touch a file somewhere in the startup scripts and search for that in the script, the script could then delete once it's run the first time.
Just be careful you deal with runtime level changes and so forth nicely.
The sysinfo() OS call gives you the time since the last reboot. This is where uptime gets it data before performing some formatting - its simpler to write you're own wrapper around this than parsing the output of uptime / working out how to read the start time of init (pid 1).
You'll also need to touch a file from your script and poll its mtime (using stat(1) from your script or stat(2) from C)
This will virtually get you there, this will check if a file has been accessed since the last boot.
If you have run the file it will have been accessed, but it also may have been edited by somebody and not run, or maybe touched.
EDIT
A bit of explanation:
LASTRUN=
ls -laru ${FILENAME}|cut -f6,7,8 -d' '|sed 's/'${FILENAME}'//g'|sed 's/^ *//;s/ *$//'
For the above command:
This will leave you a date/time ready to convert to a unix timestamp
LASTBOOT=
who -b|sed 's/.*system boot//g'|sed 's/^ *//;s/ *$//'
For the above command:
This will leave you a date/time ready to convert to a unix timestamp
the unixTimestamp function takes the Date/TIME variable and converts it to a unix timestamp and then it's just a case of seeing which is the higher number. The higher number is the most recent, so we can work out if the last thing that happened was a reboot or a file access.