← Back

Set the time zone

Defaults to Asia/Shanghai and turns on NTP sync. Pass a zone name to change it, for example UTC.

Root required

One-line run

curl -fsSL https://www.moiu.cn/scripts/timezone-set.sh | bash

Source

#!/usr/bin/env bash
# 设置时区与时间同步
#
# 默认设为 Asia/Shanghai,并打开 systemd 的自动校时。
# 用法:bash timezone-set.sh [时区]      例:bash timezone-set.sh UTC

set -e

# 需要 root:下面的系统级改动都直接执行,不再逐条 sudo
if [ "$(id -u)" -ne 0 ]; then
    echo '[!] 这个脚本需要 root 权限,请用 sudo 重新运行:'
    echo '    curl -fsSL 脚本地址 | sudo bash'
    echo '    或已经下载到本地:sudo bash 本文件'
    exit 1
fi

ZONE=Asia/Shanghai
if [ "$#" -ge 1 ]; then
    ZONE="$1"
fi

if [ ! -f "/usr/share/zoneinfo/$ZONE" ]; then
    echo "[!] 认不出这个时区:$ZONE"
    echo '    可选值形如 Asia/Shanghai / UTC / America/New_York'
    exit 1
fi

echo "====== 设置时区:$ZONE ======"

if command -v timedatectl >/dev/null 2>&1; then
    timedatectl set-timezone "$ZONE"
    timedatectl set-ntp true
    echo '[*] 已通过 timedatectl 设置,并打开 NTP 自动校时'
else
    ln -sf "/usr/share/zoneinfo/$ZONE" /etc/localtime
    echo "$ZONE" > /etc/timezone 2>/dev/null || true
    echo '[*] 没有 timedatectl,已直接改 /etc/localtime'
fi

echo ''
echo '====== 当前状态 ======'
echo "  时区:$(date +%Z)"
echo "  时间:$(date '+%Y-%m-%d %H:%M:%S')"
if command -v timedatectl >/dev/null 2>&1; then
    timedatectl show -p NTPSynchronized --value 2>/dev/null | sed 's/^/  NTP 同步:/'
fi

Download the raw file