I am trying to create a timestamp variable in a shell script to make the logging a little easier. I want to create the variable at the beginning of the script and have it print out the current time whenever I issue echo $timestamp
. It proving to be more difficult then I thought. Here are some things I've tried:
timestamp="(date +"%T")"
echo prints out (date +"%T")
timestamp="$(date +"%T")"
echo prints the time when the variable was initialized.
Other things I've tried are just slight variations that didn't work any better. Does anyone know how to accomplish what I'm trying to do?
Lots of answer but couldn't find what I was looking for :
date +"%s.%3N"
returns something like : 1606297368.210
ISO 8601 format (2018-12-23T12:34:56
) is more readable than UNIX timestamp. However on some OSs you cannot have :
in the filenames. Therefore I recommend using something like this instead:
2018-12-23_12-34-56
You can use the following command to get the timestamp in this format:
TIMESTAMP=`date +%Y-%m-%d_%H-%M-%S`
This is the format I have seen many applications use. Another nice thing about this is that if your file names start with this, you can sort them alphabetically and they would be sorted by date.
You can use
timestamp=`date --rfc-3339=seconds`
This delivers in the format 2014-02-01 15:12:35-05:00
The back-tick (`
) characters will cause what is between them to be evaluated and have the result included in the line. date --help
has other options.
And for my fellow Europeans, try using this:
timestamp=$(date +%d-%m-%Y_%H-%M-%S)
will give a format of the format: "15-02-2020_19-21-58"
You call the variable and get the string representation like this
$timestamp
Recent versions of bash
don't require call to the external program date
:
printf -v timestamp '%(%T)T'
%(...)T
uses the corresponding argument as a UNIX timestamp, and formats it according to the strftime
-style format between the parentheses. An argument of -1
corresponds to the current time, and when no ambiguity would occur can be omitted.
timestamp=$(awk 'BEGIN {srand(); print srand()}')
srand without a value uses the current timestamp with most Awk implementations.
I am using ubuntu 14.04.
The correct way in my system should be date +%s
.
The output of date +%T
is like 12:25:25
.
Use command substitution:
timestamp=$( date +%T )
If you want to get unix timestamp, then you need to use:
timestamp=$(date +%s)
%T
will give you just the time; same as %H:%M:%S
(via http://www.cyberciti.biz/faq/linux-unix-formatting-dates-for-display/)
DATE=`date "+%Y%m%d"`
DATE_WITH_TIME=`date "+%Y%m%d-%H%M%S"` #add %3N as we want millisecond too
Source: Stackoverflow.com