Introduction to Time and Epoch in Bash
In this tutorial, we will cover how to work with time and epoch in Bash. The epoch refers to January 1, 1970, at 00:00 UTC, which is used as a reference point for measuring time in seconds.
Getting the Current Time in Seconds Since the Epoch
To get the current time in seconds since the epoch, you can use the date
command with the %s
format specifier. Here’s an example:
date +%s
This will output the number of seconds that have elapsed since January 1, 1970, at 00:00 UTC.
Converting Seconds Since Epoch to Date
To convert a given number of seconds since the epoch back to a date, you can use the date
command with the --date
option and the @
symbol followed by the number of seconds. Here’s an example:
date --date @120024000
This will output the date corresponding to 120024000 seconds since the epoch.
Pure Bash Solutions
Starting from Bash 4.2, you can use the printf
command with a special format specifier to get the current time in seconds since the epoch without using any external commands. Here’s an example:
printf '%(%s)T\n' -1
This will output the number of seconds that have elapsed since January 1, 1970, at 00:00 UTC.
Alternatively, starting from Bash 5.0, you can use the built-in EPOCHSECONDS
variable to get the current time in seconds since the epoch:
echo $EPOCHSECONDS
This will output the number of seconds that have elapsed since January 1, 1970, at 00:00 UTC.
Tips and Variations
- You can use the
date
command to get the local time for a specific date or timezone. For example:
date --date='TZ="America/Los_Angeles" 09:00 next Fri'
This will output the local time for 9 AM next Friday on the west coast of the US.
- You can use the
printf
command with different format specifiers to get different types of dates or times. For example:
printf '%(%Y-%m-%d)T\n' -1
This will output the current date in the format YYYY-MM-DD
.
Conclusion
In this tutorial, we covered how to work with time and epoch in Bash using different methods, including the date
command, pure Bash solutions, and various format specifiers. With these tools and techniques, you can easily manipulate dates and times in your Bash scripts.