How to Get Timestamp in Bash
This article discusses the date
Bash command to get system date/time and UNIX timestamp.
Get Timestamp Using the date
Command in Bash
The Linux terminal uses the date
command to print the current date and time. The date
command’s simplest version can be executed without any argument.
Following is a sample output for the date
command showing the current date and time of the system:
Thu Aug 25 08:43:54 UTC 2022
We can use a different argument with the date
command to set the specific format for printing. For example, the command date +"%m-%d-%y"
outputs the date in the following format:
08-25-22
In the above command, %m
is used to show the month, %d
is used to indicate the day, and %y
is used to show the year. Similarly, we can use the date
command in many different formats.
We can print the current time only using the date +"%T"
command. %T
is used to print time only.
The output of date +"%T"
is as follows:
09:01:00
Get UNIX Timestamp
We can use the date
command to show the UNIX timestamp using the date +%s
command. The output of date +%s
is as follows:
1661417510
The above output is a UNIX timestamp.
Get Date/Time in a Bash Script
We can also use the date
command in the Bash script. Consider the following Bash script myscript.sh
to display the current date on the terminal:
#!/bin/bash
echo $(date)
When we execute the above script using ./myscript.sh
, this will print the current date on the terminal.
Store UNIX Timestamp in a Variable
We can also store the current date in any format using the date
command in a variable.
Consider the following script:
#!/bin/bash
timestamp=$(date)
echo $(timestamp)
In the following script, the timestamp
is a variable in which we are storing the current date. When we execute the above script, it will display the value of the timestamp
variable on the terminal console due to the echo
command.
Note: We can store any date and time format in a variable in the Bash script.
For example, we can use:
timestamp=$(date +%s)
to store the UNIX timestamp in the variabletimestamp
.timestamp=$(date +%T)
to store the current time in the variabletimestamp
.timestamp=$(date +"%m-%d-%y")
to store the current date in the variabletimestamp
.