|
| 1 | +#!/bin/bash |
| 2 | +#change time using hwclock and date -s |
| 3 | + |
| 4 | +clear |
| 5 | + |
| 6 | +echo "The system time is: $(date "+%Y-%m-%d %H:%M:%S %Z")" |
| 7 | +echo |
| 8 | +echo "Please enter the current date and time in UTC" |
| 9 | +echo "To find the current date and time in UTC, please check https://time.is/UTC" |
| 10 | +echo |
| 11 | + |
| 12 | +get_date () { |
| 13 | + local field_name min max |
| 14 | + field_name="$1" |
| 15 | + min="$2" |
| 16 | + max="$3" |
| 17 | + echo -n "Enter the current $field_name [$min-$max]: " |
| 18 | + read -r value |
| 19 | + echo |
| 20 | + |
| 21 | + #must be a number between $2 and $3 |
| 22 | + while [[ ! $value =~ ^[0-9]+$ ]] || [[ ${value#0} -lt $min ]] || [[ ${value#0} -gt $max ]]; |
| 23 | + do |
| 24 | + echo "Please try again, it must be a number from $min to $max." |
| 25 | + echo -n "Enter the current $field_name [$min-$max]: " |
| 26 | + read -r value |
| 27 | + echo |
| 28 | + done |
| 29 | + |
| 30 | + # Pad with zeroes to length of maximum value. |
| 31 | + # The "$((10#$value))" is needed to handle 08 and 09 correctly, which printf |
| 32 | + # would otherwise interpret as octal. This effectively strips the leading |
| 33 | + # zero by evaluating an arithmetic expression with the base set to 10. |
| 34 | + value="$(printf "%0${#max}u" "$((10#$value))")" |
| 35 | +} |
| 36 | + |
| 37 | +enter_time_and_change() |
| 38 | +{ |
| 39 | + get_date "year" "2024" "2200" |
| 40 | + year=$value |
| 41 | + get_date "month" "01" "12" |
| 42 | + month=$value |
| 43 | + get_date "day" "01" "31" |
| 44 | + day=$value |
| 45 | + get_date "hour" "00" "23" |
| 46 | + hour=$value |
| 47 | + get_date "minute" "00" "59" |
| 48 | + min=$value |
| 49 | + get_date "second" "00" "59" |
| 50 | + sec=$value |
| 51 | + |
| 52 | + if ! date -s "$year-$month-$day $hour:$min:$sec" &>/dev/null; then |
| 53 | + return 1 |
| 54 | + fi |
| 55 | + return 0 |
| 56 | +} |
| 57 | + |
| 58 | +while ! enter_time_and_change; do |
| 59 | + echo "Could not set the date to $year-$month-$day $hour:$min:$sec" |
| 60 | + read -rp "Try again? [Y/n]: " try_again_confirm |
| 61 | + if [ "${try_again_confirm^^}" = N ]; then |
| 62 | + exit 1 |
| 63 | + fi |
| 64 | + echo |
| 65 | +done |
| 66 | + |
| 67 | +hwclock -w |
| 68 | +echo "The system date has been sucessfully set to $year-$month-$day $hour:$min:$sec UTC" |
| 69 | +echo |
| 70 | + |
| 71 | +echo "Press Enter to return to the menu" |
| 72 | +echo |
| 73 | +read -r nothing |
0 commit comments