Janky NTP – Setting System Time Using HTTP

I often find myself fighting with using NTP on linux machines – usually something goes wrong: maybe ntpdate isn’t there, or for some reason UDP is blocked, or maybe for some reason it just doesn’t want to do it. Here’s my janky version of ntpdate that overcomes those issues:

date -s "$(curl -si 1.1.1.1 | grep Date: | cut -d ' ' -f 2-)" && hwclock --systohc

Here’s ChatGPT explaining this bash one-liner to you:

This command is setting the system date and time based on the date and time provided by the 1.1.1.1 server and then synchronizing the system hardware clock with the new system date and time.

Here is a breakdown of the command:

date -s "$(curl -si 1.1.1.1 | grep Date: | cut -d ' ' -f 2-)": This sets the system date and time. The curl command is used to send an HTTP request to the 1.1.1.1 server and retrieve the server’s response. The -si option tells curl to include the HTTP headers in the output and to be silent (i.e., not to show a progress meter or error messages). The output of curl is then piped to grep Date:, which searches for the string “Date:” in the output and prints the matching lines. The output of grep is then passed to cut, which extracts the second field (i.e., the date and time) from the input and prints it. The date and time is then passed as an argument to the -s option of date, which sets the system date and time to the specified value.

hwclock --systohc: This synchronizes the system hardware clock with the system date and time. The --systohc option tells hwclock to copy the system time to the hardware clock. The hardware clock is a battery-powered clock that keeps track of the time even when the system is turned off. This ensures that the system clock is set to the correct time when the system is next booted.

Of course, if NTP works for you, don’t use this.

By Yifan Gu

aka. Frank, aka. 顾屹凡

Leave a comment