Bash: How to Create a Timestamp Variable


You can use the following basic syntax to create a timestamp variable in Bash:

my_timestamp=$(date +"%Y-%m-%d_%H:%M:%S")

This particular example will create a timestamp variable named my_timestamp that contains the current date and time in the following format: YYYY-MM-DD_HH:MM:SS.

Note that the date command returns the current date and time and the + operator specifies how the current date and time should be formatted.

The following example shows how to use this syntax in practice.

Example: How to Create a Timestamp Variable in Bash

This article is currently being written on 7/25/2024.

We can use the following syntax to create a timestamp variable that holds the current date and time:

my_timestamp=$(date +"%Y-%m-%d_%H:%M:%S")

The following screenshot shows how to use this syntax in practice:

Bash create timestamp variable

Notice that when we use the echo statement to view the timestamp variable, we can see that it contains the following date and time:

  • 2024-07-25_10:12:30

Note that we can use the + operator to format the resulting timestamp in any way that we’d like.

For example, we could instead use the following syntax to only separate the date and time components of the timestamp with a single underscore:

my_timestamp=$(date +"%Y%m%d_%H%M%S")

The following screenshot shows how to use this syntax in practice:

Bash create timestamp variable with custom format

We can see that this returns the current date and time in the following format:

  • 20240725_101529

Feel free to use the + operator to format your own timestamp variable in any way that you would like.

Related Tutorials

The following tutorials explain how to perform other common tasks in Bash:

How to Compare Dates in Bash
How to Convert Timestamp to Date in Bash
How to Calculate Date Difference in Bash
How to List All Files in Folder by Date in Bash

Leave a Reply