0

my desktop CMOS battery is not working, therefore I have to set time and date each time my computer starts up. I want to create a shell script to automate the setting of date and time on my computer after each boot is complete. options that exist include: 1. buying a CMOS battery :- am considering this, but for the meantime a shell script will do. 2. using NTP to synchronize time and date with internet servers :- am not connected to the internet.

  • 2
    How your desktop is supposed to know the time? If it has no clock nor internet... ;-) Please specify more, maybe you need a script to ask you to enter the time/date at every boot? – Rmano Nov 11 '13 at 17:48
  • How do you plan on syncing with NTP servers if you're not connected to the internet? – sayantankhan Nov 11 '13 at 17:49
  • @Rmano the shell script could calculate the date dynamically, depending on the saved date when the computer was shut down last. the date must not be that accurate – patiwagura Nov 13 '13 at 13:07

1 Answers1

0

If the system has no way to know the hour, the only thing you can do is trying to save the date-time on shutdown and reload on reboot (as you suggested).

Warning: The following instruction should work with a SystemV-type init system: I have not tested it (I am on a windows machine now) so you have to test them and take them with a bit of salt --- there could be typos.

Warning2 I think that upstart (the modern Ubuntu implementation of init scripts) respect it, but your mileage can vary: test and experiments are needed.You can start from here if you want to do it in a fancier way.

To save the date on shutdown/reboot, you can add a script to the /etc/rc0.d and /etc/rc6.d directory (the first used for shutdown and the latter for reboot). The normal way to do it is to create the script in /etc/init.d and then link the script from there.

All the following commands must be issued as root. Use your preferred method...

So you can create a script /etc/init.d/savedatetime with your favorite editor and the contents:

#!/bin/sh
date +%m%d%H%M%Y.%S > /root/lastseendate.txt

make it executable and then link it (the date format is the one that date is able to read-back, see man date).

chmod +x /etc/init.d/savedatetime
cd /etc/rc0.d/
ln -s ../init.d/savedatetime K99savedatetime
cd /etc/rc6.d/
ln -s ../init.d/savedatetime K99savedatetime 

The K99 should make this script the last one executed before shutdown or reboot. If the clock is maintained through a reboot and you want do that only on shutdown, simply skip the last two commands.

Then at reboot you want to read the file. There are a lot of place where to put it, the easiest being /etc/rc.local.

Edit it and put near the start:

[ -f  /root/lastseendate.txt ] && date $(cat /root/lastseendate.txt) 
rm -f /root/lastseendate.txt

...and that should be it. Happy hacking!

Rmano
  • 31,947