【问题标题】:Getting the Canonical Time Zone name in shell script在 shell 脚本中获取规范时区名称
【发布时间】:2012-09-13 07:41:29
【问题描述】:

有没有办法从 Linux shell 脚本中获取规范时区名称?例如,如果我配置的时区是 PDT,那么我想获得“America/Los_Angeles”。

我知道如果已配置符号链接 /etc/localtime ,我可以获取它,但由于它可能未在所有服务器中配置,我不能依赖那个。
另一方面,我可以使用命令 date +%Z 获得短时区名称,但我仍然需要规范名称。

有没有办法获取当前时区的规范名称或转换使用 date +%Z 命令获取的时区,即使符号链接 /etc/localtime 未设置?

【问题讨论】:

  • 我会说“PDT”更接近于规范名称,而“America/Los_Angeles”只是帮助将位置映射到正确时区的描述性标签。
  • 我认为这是不可能的;一个缩写,即使明确扩展(例如“太平洋夏令时间”),也可以有多个对应的 TZ 数据库条目。例如,PDT不仅是America/Los_Angeles,还有America/DawsonAmerica/EnsenadaAmerica/SitkaAmerica/TijuanaAmerica/VancouverAmerica/WhitehorseUS/Pacific。 (事实上​​,如果你没有指定你想要America/Los_Angeles,我会假设你想要US/Pacific。)

标签: linux shell time timezone


【解决方案1】:

这比听起来要复杂。大多数 linux 发行版的做法都不同,因此没有 100% 可靠的方法来获取 Olson TZ 名称。

以下是我过去使用的启发式方法:

  1. 首先检查/etc/timezone,如果存在就使用它。
  2. 接下来检查 /etc/localtime 是否是指向时区数据库的符号链接
  3. 否则在 /usr/share/zoneinfo 中查找具有相同内容的文件 作为文件 /etc/localtime

未经测试的示例代码:

if [ -f /etc/timezone ]; then
  OLSONTZ=`cat /etc/timezone`
elif [ -h /etc/localtime ]; then
  OLSONTZ=`readlink /etc/localtime | sed "s/\/usr\/share\/zoneinfo\///"`
else
  checksum=`md5sum /etc/localtime | cut -d' ' -f1`
  OLSONTZ=`find /usr/share/zoneinfo/ -type f -exec md5sum {} \; | grep "^$checksum" | sed "s/.*\/usr\/share\/zoneinfo\///" | head -n 1`
fi

echo $OLSONTZ

请注意,这个快速示例不处理多个 TZ 名称与给定文件匹配的情况(在 /usr/share/zoneinfo 中查找时)。消除适当的 TZ 名称的歧义将取决于您的应用程序。

-尼克

【讨论】:

  • 嗯,这不是我想要的,但它会起作用。谢谢:)
  • 我使用了这个而不是使用 md5 并且还阻止了 posixrules 文件中的匹配:find /usr/share/zoneinfo -type f ! -name 'posixrules' -exec cmp -s {} /etc/localtime \; -print | sed -e 's@.*/zoneinfo/@@' | head -n1
  • 我发现Etc 目录只包含数字时区,所以我将它们从@user9645 的find 中排除:! -regex ".*/Etc/.*"
  • 对于 OSX 你应该使用/var/db/timezone/zoneinfo/ 而不是/usr/share/zoneinfo/
猜你喜欢
  • 2021-11-28
  • 1970-01-01
  • 1970-01-01
  • 2015-05-21
  • 2017-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多