Linux獲取目前時區為
獲取目前時區為 Region/City
可惜
timedatectl set-timezone
不更新/etc/timezone
。如何獲得目前時區
Region/City
,例如,給定:% timedatectl | grep zone Time zone: Asia/Kuala_Lumpur (+08, +0800)
我可以得到最後一部分:
% date +"%Z %z" +08 +0800
我如何在
Asia/Kuala_Lumpur
不獲得所有awk
病房的情況下獲得零件?我在 Linux 上,但也有 POSIX 方式嗎?
timedatectl
是通過執行 a onsystemd
查詢並派生時區名稱(如)的東西。如果不是符號連結,則無法派生該名稱,因為那些時區定義文件不包含該資訊。timedated``dbus``timedated``Europe/London``readlink()``/etc/localtime``/etc/localtime
基於此和tonioc的評論,我整理了以下內容:
#!/bin/bash set -euo pipefail if filename=$(readlink /etc/localtime); then # /etc/localtime is a symlink as expected timezone=${filename#*zoneinfo/} if [[ $timezone = "$filename" || ! $timezone =~ ^[^/]+/[^/]+$ ]]; then # not pointing to expected location or not Region/City >&2 echo "$filename points to an unexpected location" exit 1 fi echo "$timezone" else # compare files by contents # https://stackoverflow.com/questions/12521114/getting-the-canonical-time-zone-name-in-shell-script#comment88637393_12523283 find /usr/share/zoneinfo -type f ! -regex ".*/Etc/.*" -exec \ cmp -s {} /etc/localtime \; -print | sed -e 's@.*/zoneinfo/@@' | head -n1 fi