Create timestamp variable in bash script

BashVariablesTimestamp

Bash Problem Overview


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?

Bash Solutions


Solution 1 - Bash

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/)

Solution 2 - Bash

In order to get the current timestamp and not the time of when a fixed variable is defined, the trick is to use a function and not a variable:

#!/bin/bash

# Define a timestamp function
timestamp() {
  date +"%T" # current time
}

# do something...
timestamp # print timestamp
# do something else...
timestamp # print another timestamp
# continue...

If you don't like the format given by the %T specifier you can combine the other time conversion specifiers accepted by date. For GNU date, you can find the complete list of these specifiers in the official documentation here: https://www.gnu.org/software/coreutils/manual/html_node/Time-conversion-specifiers.html#Time-conversion-specifiers

Solution 3 - Bash

DATE=`date "+%Y%m%d"`

DATE_WITH_TIME=`date "+%Y%m%d-%H%M%S"` #add %3N as we want millisecond too

Solution 4 - Bash

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.

Solution 5 - Bash

You can refer to the following table to generate time stamp as you want:

        Format/result           |       Command              |          Output
--------------------------------+----------------------------+------------------------------
YYYY-MM-DD                      | date -I                    | $(date -I)
YYYY-MM-DD_hh:mm:ss             | date +%F_%T                | $(date +%F_%T)
YYYYMMDD_hhmmss                 | date +%Y%m%d_%H%M%S        | $(date +%Y%m%d_%H%M%S)
YYYYMMDD_hhmmss (UTC version)   | date --utc +%Y%m%d_%H%M%SZ | $(date --utc +%Y%m%d_%H%M%SZ)
YYYYMMDD_hhmmss (with local TZ) | date +%Y%m%d_%H%M%S%Z      | $(date +%Y%m%d_%H%M%S%Z)
YYYYMMSShhmmss                  | date +%Y%m%d%H%M%S         | $(date +%Y%m%d%H%M%S)
YYYYMMSShhmmssnnnnnnnnn         | date +%Y%m%d%H%M%S%N       | $(date +%Y%m%d%H%M%S%N)
YYMMDD_hhmmss                   | date +%y%m%d_%H%M%S        | $(date +%y%m%d_%H%M%S)
Seconds since UNIX epoch:       | date +%s                   | $(date +%s)
Nanoseconds only:               | date +%N                   | $(date +%N)
Nanoseconds since UNIX epoch:   | date +%s%N                 | $(date +%s%N)
ISO8601 UTC timestamp           | date --utc +%FT%TZ         | $(date --utc +%FT%TZ)
ISO8601 UTC timestamp + ms      | date --utc +%FT%T.%3NZ     | $(date --utc +%FT%T.%3NZ)
ISO8601 Local TZ timestamp      | date +%FT%T%Z              | $(date +%FT%T%Z)
YYYY-MM-DD (Short day)          | date +%F\(%a\)             | $(date +%F\(%a\))
YYYY-MM-DD (Long day)           | date +%F\(%A\)             | $(date +%F\(%A\))

Solution 6 - Bash

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

Solution 7 - Bash

Use command substitution:

timestamp=$( date +%T )

Solution 8 - Bash

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.

Solution 9 - Bash

A lot of answers but couldn't find what I was looking for :

date +"%s.%3N"

returns something like : 1606297368.210

Solution 10 - Bash

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.

Solution 11 - Bash

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.

Solution 12 - Bash

timestamp=$(awk 'BEGIN {srand(); print srand()}')

srand without a value uses the current timestamp with most Awk implementations.

Solution 13 - Bash

This is a little more than you asked, so you can customize it to your needs.

> I am trying to create a timestamp variable in a shell script...

This script will allow you to create a variable. Though I'm not entirely sure how reusable is when changing the shell context. But it will do the job.

function timestamp {
    TEXT="Date:"
	DATE=`date +%Y-%m-%d`
	TIME=`date +%H:%M:%S`
	ZONE=`date +"%Z %z"`
	echo $TEXT $DATE $TIME $ZONE
}

function fulldate {
  timevariable=$(timestamp)
  echo $timevariable
}

echo "- Output 1:"
timestamp
echo "- Output 2:"
fulldate
echo "- Output 3:"
echo $timevariable

Outputs:

- Output 1:
Date: 2021-08-12 23:28:08 UTC +0000
- Output 2:
Date: 2021-08-12 23:28:08 UTC +0000
- Output 3:
Date: 2021-08-12 23:28:08 UTC +0000

I've tested this working on GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)

Solution 14 - Bash

If performance is a concern, @chepner's answer is a clear winner.

With a bit more complexity, you can also get micro- or milli- second granularity using only bash built-ins. Below is an example of a function that emits the current timestamp including milliseconds:

timestamp() {
    IFS=. read S US <<<$EPOCHREALTIME # Read epoch seconds/microseconds
    MS=$((10#$US/1000)) # Convert to milliseconds (interpret in base-10, even with leading 0)
    printf '%(%F %T)T.%03i' $S $MS # Emit formatted timestamp
}

TS=$(timestamp) # Invoke function, assign to variable

Note that the printf format can be adjusted emit your preferred date/time format.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - BashdchakarovView Answer on Stackoverflow
Solution 2 - BashgiordanoView Answer on Stackoverflow
Solution 3 - BashGirdhar Singh RathoreView Answer on Stackoverflow
Solution 4 - BashCanerView Answer on Stackoverflow
Solution 5 - BashInsteinView Answer on Stackoverflow
Solution 6 - BashChristoffer NissenView Answer on Stackoverflow
Solution 7 - BashchorobaView Answer on Stackoverflow
Solution 8 - BashSean LinView Answer on Stackoverflow
Solution 9 - BashLoïcView Answer on Stackoverflow
Solution 10 - BashBillView Answer on Stackoverflow
Solution 11 - BashchepnerView Answer on Stackoverflow
Solution 12 - BashZomboView Answer on Stackoverflow
Solution 13 - Bashcarloswm85View Answer on Stackoverflow
Solution 14 - BashpamphletView Answer on Stackoverflow