Getting the Canonical Time Zone name in shell script
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:
- First check /etc/timezone, if it exists use it.
- Next check if /etc/localtime is a symlink to the timezone database
- 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
how to get local date/time in linux terminal while server configured in UTC/different timezone?
Use the TZ
environment variable to pass the desired timezone to date
:
TZ=<timezone> date
You can find the available timezones in the /usr/share/zoneinfo/
directory and subdirectories. For example, /usr/share/zoneinfo/America/New_York
defines TZ=America/New_York
.
Example:
$ date
Fri Jul 29 06:31:53 BDT 2016
$ TZ='America/New_York' date
Thu Jul 28 20:31:58 EDT 2016
$ TZ='America/Los_Angeles' date
Thu Jul 28 17:31:54 PDT 2016
How to obtain the absolute path of a file via Shell (BASH/ZSH/SH)?
Use realpath
$ realpath example.txt
/home/username/example.txt
Reliable way for a Bash script to get the full path to itself
Here's what I've come up with (edit: plus some tweaks provided by sfstewman, levigroker, Kyle Strand, and Rob Kennedy), that seems to mostly fit my "better" criteria:
SCRIPTPATH="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )"
That SCRIPTPATH
line seems particularly roundabout, but we need it rather than SCRIPTPATH=`pwd`
in order to properly handle spaces and symlinks.
The inclusion of output redirection (>/dev/null 2>&1
) handles the rare(?) case where cd
might produce output that would interfere with the surrounding $( ... )
capture. (Such as cd
being overridden to also ls
a directory after switching to it.)
Note also that esoteric situations, such as executing a script that isn't coming from a file in an accessible file system at all (which is perfectly possible), is not catered to there (or in any of the other answers I've seen).
The --
after cd
and before "$0"
are in case the directory starts with a -
.
How do I know the script file name in a Bash script?
me=`basename "$0"`
For reading through a symlink1, which is usually not what you want (you usually don't want to confuse the user this way), try:
me="$(basename "$(test -L "$0" && readlink "$0" || echo "$0")")"
IMO, that'll produce confusing output. "I ran foo.sh, but it's saying I'm running bar.sh!? Must be a bug!" Besides, one of the purposes of having differently-named symlinks is to provide different functionality based on the name it's called as (think gzip and gunzip on some platforms).
1 That is, to resolve symlinks such that when the user executes foo.sh
which is actually a symlink to bar.sh
, you wish to use the resolved name bar.sh
rather than foo.sh
.
How can I get a human-readable timezone name in Python?
This may not have been around when this question was originally written, but here is a snippet to get the time zone official designation:
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
Further, this can be used with a non-naive datetime object (aka a datetime where the actual timezone has been set using pytz.<timezone>.localize(<datetime_object>)
or datetime_object.astimezone(pytz.<timezone>)
as follows:
>>> import datetime, pytz
>>> todaynow = datetime.datetime.now(tz=pytz.timezone('US/Hawaii'))
>>> todaynow.tzinfo # turned into a string, it can be split/parsed
<DstTzInfo 'US/Hawaii' HST-1 day, 14:00:00 STD>
>>> todaynow.strftime("%Z")
'HST'
>>> todaynow.tzinfo.zone
'US/Hawaii'
This is, of course, for the edification of those search engine users who landed here. ... See more at the pytz module site.
Get a list of valid time zones in Go
To get a list of time zones, you can use something like:
package main
import (
"fmt"
"io/ioutil"
"strings"
)
var zoneDirs = []string{
// Update path according to your OS
"/usr/share/zoneinfo/",
"/usr/share/lib/zoneinfo/",
"/usr/lib/locale/TZ/",
}
var zoneDir string
func main() {
for _, zoneDir = range zoneDirs {
ReadFile("")
}
}
func ReadFile(path string) {
files, _ := ioutil.ReadDir(zoneDir + path)
for _, f := range files {
if f.Name() != strings.ToUpper(f.Name()[:1]) + f.Name()[1:] {
continue
}
if f.IsDir() {
ReadFile(path + "/" + f.Name())
} else {
fmt.Println((path + "/" + f.Name())[1:])
}
}
}
output:
Africa/Abidjan
Africa/Accra
Africa/Addis_Ababa
Africa/Algiers
Africa/Asmara
Africa/Asmera
Africa/Bamako
Africa/Bangui
...
Related Topics
.Htaccess Redirect Index.PHP to /
How to Use Linux Hugetlbfs for Shared Memory Maps of Files
Awk, Pipe and Tail -F Giving Unexpected Behavior
How to Clear Space on My Main System Drive on a Linux Centos System
What Are The Lowest Possible Permissions for Typo3
Analog of Com Programming in Linux/Unix
Setup Sftp to Use Public-Key Authentication
How to Compare Two Text Files for The Same Exact Text Using Bash
Haskell Cabal: Mysterious Missing or Recursive Dependencies
Linux X86 Nasm - Subroutine: Print a Dword from Eax
Programmatically Disable Hardware Prefetching on Amd Systems
Error Message When Setting Up Adt in Linux
Is There Any Posix Way Through Fstat() to Check Whether a File Is a Symbolic Link or Not
Webdrivererror Error: Chrome Failed to Start: Exited Abnormally
How Existing Kernel Driver Should Be Initialized as Pci Memory-Mapped
$${Home} or ${Home} in Makefile
What Is The Maximum Number of Subdirectories Allowed in Ext4