How to Get Epoch Timestamps in Bash and Linux
Get and convert Unix epoch timestamps from the command line using date, awk, and other Linux tools. Useful for shell scripts, log analysis, and cron jobs.
Programming
Detailed Explanation
Epoch Timestamps in Bash and Linux
The Linux date command is the primary tool for working with epoch timestamps on the command line. It supports both getting the current epoch and converting between formats.
Getting the Current Epoch
# Seconds since epoch
date +%s
# 1705312200
# Milliseconds (using date and nanoseconds)
echo $(($(date +%s%N) / 1000000))
# 1705312200000
# Nanoseconds
date +%s%N
# 1705312200000000000
Converting Epoch to Human-Readable
# GNU date (Linux)
date -d @1705312200
# Mon Jan 15 09:30:00 UTC 2024
date -d @1705312200 +"%Y-%m-%d %H:%M:%S"
# 2024-01-15 09:30:00
# BSD date (macOS)
date -r 1705312200
date -r 1705312200 +"%Y-%m-%d %H:%M:%S"
Converting Human-Readable to Epoch
# GNU date
date -d "2024-01-15 09:30:00 UTC" +%s
# 1705312200
# Relative dates
date -d "tomorrow" +%s
date -d "next monday" +%s
date -d "+1 hour" +%s
date -d "2 days ago" +%s
Countdown in Bash
#!/bin/bash
target=$(date -d "2025-01-01 00:00:00 UTC" +%s)
now=$(date +%s)
diff=$((target - now))
days=$((diff / 86400))
hours=$(( (diff % 86400) / 3600 ))
minutes=$(( (diff % 3600) / 60 ))
seconds=$((diff % 60))
echo "Countdown: ${days}d ${hours}h ${minutes}m ${seconds}s"
Practical Scripts
Log timestamp extraction:
# Convert log timestamps to epoch for sorting
awk '{print $1}' access.log | while read ts; do
date -d "$ts" +%s
done
File age check:
file_epoch=$(stat -c %Y /path/to/file)
now=$(date +%s)
age_hours=$(( (now - file_epoch) / 3600 ))
echo "File is ${age_hours} hours old"
Use Case
Use these commands in shell scripts, cron jobs, log analysis pipelines, and DevOps automation. Bash epoch manipulation is essential for any Linux administrator or developer who works with timestamps in scripts.