Last active
January 11, 2022 11:53
-
-
Save kou1okada/dc4702899ace8626e74582b0dfedfbaf to your computer and use it in GitHub Desktop.
httpdate.sh - Get date information from http.
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
#!/usr/bin/env bash | |
# | |
# httpdate.sh - Get date information from http | |
# Copyright (c) 2017 Koichi OKADA. All rights reserved. | |
# This script is distributed under the MIT license. | |
# | |
function help () | |
{ | |
cat<<-EOD | |
Usage: "$(basename "$0")" [options] [URL] | |
Options: | |
-u, --url URL Set url to get date. | |
EOD | |
} | |
ARGS=() | |
OPT_URL=https://google.com/ | |
while (( 0 < $# )); do | |
case "$1" in | |
-h|--help) | |
OPT_HELP="$1" | |
shift | |
;; | |
-u|--url) | |
OPT_URL="$1" | |
shift | |
;; | |
--offset) | |
OPT_OFFSET="$2" | |
shift 2 | |
;; | |
--*) | |
echo "ERROR: unknown option ${1}" | |
exit 1 | |
;; | |
--) | |
ARGS+=( "${@:2}" ) | |
shift $# | |
;; | |
*) | |
ARGS+=( "$1" ) | |
shift | |
;; | |
esac | |
done | |
if [ -n "$OPT_HELP" ] || (( 1 < ${#ARGS[@]} )); then | |
help | |
exit 1 | |
fi | |
if (( 1 == ${#ARGS[@]} )); then | |
OPT_URL="${ARGS[0]}" | |
fi | |
HTTP="$(wget -qSO/dev/null "$OPT_URL" |& grep Date: | tail -n1 |sed 's/.*Date: *//g')" | |
LOCAL="$(LANG=C date)" | |
OFFSET="$(( $(date -d "$LOCAL" +%s) - $(date -d "$HTTP" +%s) + ${OPT_OFFSET:-0} ))" | |
OFFSET_SIGN="$( (( OFFSET < 0 )) && echo -n - || echo -n +)" | |
OFFSET_ABS="$(( ${OFFSET_SIGN}1 * OFFSET ))" | |
OFFSET_HR="$(\ | |
printf "%s%d d %02d:%02d:%02d" \ | |
"${OFFSET_SIGN}" \ | |
$(( OFFSET_ABS / 86400 )) \ | |
$(( OFFSET_ABS % 86400 / 3600 )) \ | |
$(( OFFSET_ABS % 3600 / 60 )) \ | |
$(( OFFSET_ABS % 60 )) )" | |
echo -n "http : "; date -d "$HTTP" | |
echo -n "local : "; date -d "$LOCAL" | |
echo "offset : $OFFSET s ($OFFSET_HR)" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment