Created
January 27, 2015 12:03
-
-
Save bllngr/49f413268186d1a36a13 to your computer and use it in GitHub Desktop.
Synchronize time between hardware clock and NTP server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# | |
# Author: Thomas (https://raspberrypi.stackexchange.com/users/9732/thomas) | |
# Modified-by: Julius Bullinger (https://github.com/sqrt) | |
# Version: 0.2 | |
# | |
# Synchronize time between hardware clock and NTP server | |
# Make sure only root can run this script | |
if [[ $EUID -ne 0 ]]; then | |
echo "This script must be run as root." 1>&2 | |
exit 1 | |
fi | |
# Location of logfile | |
LOGFILE="/var/log/ntp2hwc.log" | |
if [ ! -f $LOGFILE ]; then | |
touch $LOGFILE | |
fi | |
# Set the maximum allowed difference in seconds between Hardware and System Clock | |
max_diff="1" | |
msg_connection="Connected to NTP server." | |
msg_noconnection="No connection to NTP server." | |
# Check for NTP connection | |
if ( ntpq -p | grep -q "^\*" ); then | |
echo "$msg_connection" | |
echo "---------------------------------" | |
hwclock_secs=$(sudo hwclock --debug | grep "^Hw clock time" | awk '{print $(NF-3)}') | |
echo "Hardware Clock : $hwclock_secs sec" | |
sysclock_secs=$(date +"%s") | |
echo "System Clock : $sysclock_secs sec" | |
echo "---------------------------------" | |
# Absolute difference between the two clocks | |
clock_diff=$((hwclock_secs-sysclock_secs)) | |
clock_diff=${clock_diff#-} | |
echo "Difference: $clock_diff sec" | |
msg_diff="Hardware Clock difference: $clock_diff sec" | |
if [ "$clock_diff" -gt "$max_diff" ] ; then | |
echo "---------------------------------" | |
echo "The difference between Hardware and System Clock is more than $max_diff sec." | |
echo "Hardware Clock will be updated" | |
# Update hwclock from system clock | |
sudo hwclock -w | |
msg_diff="$msg_diff --> HW-Clock updated." | |
fi | |
if ! (awk '/./{line=$0} END{print line}' $LOGFILE | grep -q "$msg_connection") || [ "$clock_diff" -gt "$max_diff" ]; then | |
echo "$(date): $msg_connection. $msg_diff" >> $LOGFILE | |
fi | |
else | |
# No NTP connection | |
echo "$msg_noconnection" | |
if ! (awk '/./{line=$0} END{print line}' $LOGFILE | grep -q "$msg_noconnection"); then | |
echo "$(date): $msg_noconnection" >> $LOGFILE | |
fi | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment