Last active
June 20, 2025 09:34
-
-
Save theabbie/e2ed0b813566a251c8e5d3f70df7a7bd to your computer and use it in GitHub Desktop.
Terminal clock with NTP sync bash script
This file contains hidden or 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 | |
tz_hours=0 | |
tz_minutes=0 | |
while [[ $# -gt 0 ]]; do | |
case "$1" in | |
-h) tz_hours="$2"; shift 2 ;; | |
-m) tz_minutes="$2"; shift 2 ;; | |
*) exit 1 ;; | |
esac | |
done | |
tz_offset_seconds=$((tz_hours * 3600 + tz_minutes * 60)) | |
fetch_ntp() { | |
msg=$(printf '\x1b\0%.0s' {1..47}) | |
response=$(echo -ne "$msg" | socat -T 2 - UDP:time.google.com:123 2>/dev/null) | |
[[ -z "$response" ]] && return | |
hex=$(echo -n "$response" | hexdump -v -e '1/1 "%02x"') | |
transmit_ts_hex=${hex:80:8} | |
ntp_seconds=$((16#${transmit_ts_hex})) | |
unix_seconds=$((ntp_seconds - 2208988800)) | |
ntp_time=$unix_seconds | |
local_time=$(date +%s) | |
} | |
print_time() { | |
formatted=$(date -u -r "$1" "+%A, %d %B %Y at %I:%M:%S %p") | |
echo -e "\033[H\033[J$formatted" | |
} | |
fetch_ntp | |
count=0 | |
while true; do | |
now=$(date +%s) | |
diff=$((now - local_time)) | |
current=$((ntp_time + diff + tz_offset_seconds)) | |
print_time "$current" | |
sleep 1 | |
count=$((count + 1)) | |
((count % 60 == 0)) && fetch_ntp | |
done |
Author
theabbie
commented
Jun 20, 2025
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment