在Shell脚本中获取规范时区名称 [英] Getting the Canonical Time Zone name in shell script

查看:753
本文介绍了在Shell脚本中获取规范时区名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种从Linux Shell脚本获取规范时区名称的方法?例如,如果我配置的时区是PDT,那么我想得到"America/Los_Angeles".

Is there a way of getting the Canonical Time Zone name from a Linux shell script? for example, if my configured time zone is PDT, then I would like to get "America/Los_Angeles".

我知道我可以从符号链接/etc/localtime中获得(如果已配置),但是由于可能未在所有服务器中都进行配置,因此我不能依赖该服务器.
另一方面,我可以使用命令日期+%Z获得短时区名称,但是我仍然需要规范名称.

I know I could get from the symbolic link /etc/localtime if it were configured, but as it might not be configured in all servers I cannot rely on that one.
On the other hand, I can get the short time zone name with the command date +%Z, but I still need the canonical name.

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

Is there a way to either get the canonical name of the current time zone or transform the time zone gotten with the date +%Z command, even if the symbolic link /etc/localtime is not set?

推荐答案

这比听起来复杂得多.大多数Linux发行版的操作方式都不同,因此没有100%可靠的方法来获得Olson TZ名称.

This is more complicated than it sounds. Most linux distributions do it differently so there is no 100% reliable way to get the Olson TZ name.

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

Below is the heuristic that I have used in the past:

  1. 首先检查/etc/timezone,如果存在,请使用它.
  2. 接下来检查/etc/localtime是否为时区数据库的符号链接
  3. 否则在/usr/share/zoneinfo中找到具有相同内容的文件 作为文件/etc/localtime
  1. First check /etc/timezone, if it exists use it.
  2. Next check if /etc/localtime is a symlink to the timezone database
  3. Otherwise find a file in /usr/share/zoneinfo with the same content as the file /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名称将取决于您的应用程序.

Note that this quick example does not handle the case where multiple TZ names match the given file (when looking in /usr/share/zoneinfo). Disambiguating the appropriate TZ name will depend on your application.

-尼克

这篇关于在Shell脚本中获取规范时区名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆