How to Get Timestamp in Bash [2 Practical Cases]

LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now

The Bash date command is multi-functional, offering various options and formats to display date and time. With this command, you can generate a timestamp that’s useful for logging and other purposes. This article demonstrates how to obtain a timestamp in Bash using the date command.

Key Takeaways

  • Learning about the date command.
  • Creating timestamp using the date command.
  • Use of timestamp for logging purposes.

Free Downloads

2 Cases for Getting Timestamp in Bash

The date command usually shows both the date and time. But if you want time only in your timestamp, you have to use format specifiers that tell it how you want the time to appear. Take a look at the below scripts to see how you can create a customized timestamp with just the time part.

Case 1: Get Timestamp in Local Time Using Bash Script

Using the format specifier %T you can exact the time part of the date command. This will print time in %H:%M:%S format. However, you can also use %H:%M:%S format specifiers to get the same result.

Steps to Follow >

❶ At first, launch an Ubuntu Terminal.

❷ Write the following command to open a file named localtime.sh in the build-in nano editor:

nano localtime.sh
EXPLANATION
  • nano: Opens a file in the Nano text editor.
  • localtime.sh: Name of the file.
Creating a Bash script file in nano❸ Copy the following scripts and paste them into nano. Press CTRL+O and ENTER to save the file; CTRL+X to exit. Alternatively, copy the following script. Paste the script in a text editor and save it as .sh file.

Script (localtime.sh) >

#!/bin/bash

timestamp=$(date +%T)
echo $timestamp
EXPLANATION

In the script, the %T format specifier is used with the date command, which retrieves the current local time in the hh:mm:ss format. This local time is then stored in the timestamp variable. The echo command is used to display the variable, which effectively prints the current time to the terminal when the script is run.

❹ Use the following two commands to make both file executable:

chmod u+x localtime.sh
EXPLANATION
  • chmod: Changes permissions.
  • u+x: Giving the owner executing permission.
  • localtime.sh: Name of the script.
Changing permission of a script❺ Run the localtime.sh script by the following command:

./localtime.sh

Timestamp in local timeAs you can see the timestamp variable contains the local time which can be used as a timestamp.

NOTE: If you want to get a timestamp that will be always updated with current time then get the timestamp by creating a function or Bash script. If you take it in a variable then it will not be updated to the current time.

Case 2: Getting Timestamp in UTC time Using Bash

To get the timestamp in UTC time you can use the -u option of date command. Here is how you can achieve it.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (utctime.sh) >

#!/bin/bash

timestamp=$(date -u +%T)
echo $timestamp
EXPLANATION

In the script, the -u flag is used along with the %T format specifier within the date command. This combination gives the current time in UTC and formats it as hh:mm:ss. The obtained UTC time is then stored in the timestamp variable. Finally, the echo command is used to display the value stored in the timestamp variable.

Run the utctime.sh script by the following command:

./utctime.sh

Timestamp in UTC timeHere -u option successfully generates UTC time as shown in the image above. This can be used as a timestamp where necessary.

How to Get Timestamp in UNIX Epoch

A Unix timestamp is represented as seconds since January 1, 1970. To get a timestamp in Unix time epoch use %s option of date command.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (unixtime.sh) >

#!/bin/bash

timestamp=$(date +%s)
echo $timestamp
EXPLANATION

The +%s option captures the current time in Unix timestamp, which represents the number of seconds elapsed since January 1, 1970, UTC. The obtained timestamp is stored in the timestamp variable. Later the echo command is used to display it.

Run the unixtime.sh script by the following command:

./unixtime.sh

Timestamp in Unix timeHere you can see a timestamp that basically counts time in seconds since January 1, 1970.

Effective Use of Timestamp in Bash

Let’s say you want a timestamp for logging purpose or keeping track of system updates. In the following demonstration I am going to write a similar script that can updates system in each 100 seconds epoch and add a timestamp in a log file for each update.

You can follow the Steps of Case 1 to learn about creating and saving shell scripts.

Script (timestamp.sh) >

#!/bin/bash

log_file="update.log"

# Check if the log file exists, if not, create it
if [ ! -e "$log_file" ]; then
touch "$log_file"
fi

while true; do
timestamp=$(date +%s.)
sudo apt update
echo "System updated at: $timestamp" >> "$log_file"
sleep 100
done
EXPLANATION

This Bash script initializes a variable named log_file with the value update.log. It checks whether the specified log file exists; if not, it creates the file using the touch command. The script then enters an infinite loop while loop. Within each iteration of the loop, it captures the current Unix timestamp in seconds using the date command.

Then it proceeds to update the system’s package information using sudo apt update. After the update, it appends the timestamp to the log file, indicating that the system was updated in the corresponding timestamp. The loop pauses for 100 seconds using the sleep command before starting the next iteration.

Run the timestamp.sh script by the following command:

./timestamp.sh

Timestamp for system update logOnce you run the code it will update the system in each 100s and add update notice with Unix timestamp in the update.log file.

Let’s see the timestamp of each update in update.log file.

Content of update logAs you can see update.log contains two timestamps in it. Last one indicates the time when the system is lastly updated using timestamp.sh script.

Conclusion

In summary, getting a timestamp in Bash is straightforward using the date command. Utilizing timestamps efficiently simplifies tasks for system administrators, enabling easy tracking of modification times and investigations into recent changes. After reading this article hope you can easily use timestamps in Bash.

People Also Ask

How to convert timestamps to date in Bash?
To convert timestamps to date in Bash use date command with -d option. For example, date -d @1692686155 will convert the timestamp 1692686155 into human-readable time and date.
How to I get current Unix time in milliseconds?
To get Unix time with milliseconds precision use +”%s.%3N” format specifiers with the date command. This will effectively print time in seconds since Unix Epoch upto three decimal points, in other words, milliseconds.
What is the best way to compare timestamps in Bash?
Use if statement with -nt or -eq comparison operator to compare between two timestamps whether they refer to the same time or not.

Related Articles


<< Go Back to Bash Script Examples | Bash Scripting Basics | Bash Scripting Tutorial

Rate this post
Md Zahidul Islam Laku

Hey, I'm Zahidul Islam Laku currently working as a Linux Content Developer Executive at SOFTEKO. I completed my graduation from Bangladesh University of Engineering and Technology (BUET). I write articles on a variety of tech topics including Linux. Learning and writing on Linux is nothing but fun as it gives me more power on my machine. What can be more efficient than interacting with the Operating System without Graphical User Interface! Read Full Bio

Leave a Comment