Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the Canonical Time Zone name in shell script

Tags:

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".

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.

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?

like image 709
Nacho Mezzadra Avatar asked Sep 20 '12 21:09

Nacho Mezzadra


People also ask

How do I find the timezone in Shell?

We can use the date command to view the timezone. Simply type the Linux command date in the terminal and you will get the required output.

Where is timezone file in Linux?

The timezone information files used by tzset(3) are typically found under a directory with a name like /usr/share/zoneinfo.


1 Answers

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. 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

Untested example code:

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 

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.

-nick

like image 124
mythagel Avatar answered Sep 30 '22 20:09

mythagel