Converting an Epoch Timestamp to a Readable Date in Bash

You're staring at a log file from your Graylog instance or a cron job output, and the timestamp column reads 1700000000. You could open a browser tab and type "epoch converter," but that's a context switch you don't need. A thirty-line bash script handles it in under a millisecond, works offline, and gives you exactly the format you asked for. No JavaScript runtime, no Python one-liner with three imports.

The script below does one thing: takes an integer Unix timestamp and prints a date string. Two flags control the output. -u forces UTC instead of your local timezone. -i switches from date's default human-readable format to ISO 8601. That's the entire feature set. No dependencies beyond what ships with any Linux base image.

Verified terminal output of example.sh — real test runs in a clean, network-isolated container.

Why set -euo pipefail

The first line after the shebang is non-negotiable in my scripts. -e means the script dies immediately if any command returns a non-zero exit code. -u catches references to unset variables before they propagate into garbled output. -o pipefail ensures that if you ever pipe a command into another, a failure on the left side isn't swallowed by the right side's success. For a script this short, the flag that matters most is -u: if someone removes the ts="" initialization and the argument-parsing loop never assigns it, you want a hard error, not a silent empty string passed into date -d "@${ts}".

Argument Parsing

The while [ $# -gt 0 ] loop with a case statement is the standard POSIX way to handle flags. I could have used getopts, but getopts doesn't let you cleanly reject non-numeric positional arguments with a custom error message that names the offending value. Here's what each branch does:

  • -u sets utc=1. Later, this becomes the -u flag passed to date.
  • -i sets iso=1. This changes the format string in the final date call.
  • -h prints usage to stderr and exits 1.
  • -- is the standard "end of options" marker. Everything after it is treated as positional data. In practice, for a single-argument script, it's a safety net against edge cases.
  • The * catch-all is where validation lives. The regex ^-?[0-9]+$ accepts integers including negatives (for pre-1970 timestamps) and rejects everything else. If the input doesn't match, you get a specific error naming the bad value, and the script exits 1 immediately.

After the loop, there's a guard: if ts is still empty, the user provided only flags or no arguments at all. The script prints an error to stderr and calls usage, which also exits 1. This catches the bare invocation where someone types the script name and hits Enter expecting something to happen.

The date Call

GNU date (what you get on Ubuntu, Debian, and most Linux distros) accepts -d "@<epoch>" to interpret a number as seconds since the Unix epoch. The format string determines what comes out:

  • Default (no -i): date -d "@$ts" prints something like Tue Nov 14 22:13:20 UTC 2023. Readable for a human, but not machine-parseable without extra work.
  • ISO with local timezone (-i only): the format is %Y-%m-%dT%H:%M:%S%z, producing 2023-11-14T22:13:20+0000. The %z specifier gives you a numeric UTC offset like +0530.
  • ISO with UTC (-u -i): the format is %Y-%m-%dT%H:%M:%SZ, producing 2023-11-14T22:13:20Z. The literal Z suffix means "UTC" per the ISO 8601 spec.

I split these into separate branches rather than building one conditional format string because mixing %z and a literal Z in a single expression gets confusing fast, and the logic is easier to audit when each output path is explicit.

Verification

I ran this in a clean Ubuntu container. Every test passed on the first run. A few outputs worth noting:

$ bash example.sh 1700000000
Tue Nov 14 22:13:20 UTC 2023

$ bash example.sh -u -i 1700000000
2023-11-14T22:13:20Z

$ bash example.sh -u -i 4102444800
2100-01-01T00:00:00Z

$ bash example.sh -u -i -1
1969-12-31T23:59:59Z

The negative epoch test matters. If you're processing logs from a system that was misconfigured before 1970 (yes, this happens with embedded devices and old NTP fallbacks), -1 should give you one second before the epoch, and it does. The large-epoch test confirms the script doesn't overflow or truncate at year 2100.

Error handling also behaved correctly:

$ bash example.sh not_a_number
Error: "not_a_number" is not a valid integer epoch.

$ bash example.sh
Error: exactly one non-empty epoch integer required.
Usage: epoch2date [-u] [-i] <epoch>
  -u  Force UTC (default: local timezone)
  -i  Output ISO 8601 format

Both exit with status 1. No stack traces, no "command not found" noise leaking into your terminal.

The Script

#!/usr/bin/env bash
set -euo pipefail

SCRIPT="epoch2date"

usage() {
  printf 'Usage: %s [-u] [-i] <epoch>\n' "$SCRIPT" >&2
  printf '  -u  Force UTC (default: local timezone)\n' >&2
  printf '  -i  Output ISO 8601 format\n' >&2
  exit 1
}

utc=0
iso=0
ts=""

while [ $# -gt 0 ]; do
  case "$1" in
    -u) utc=1 ;;
    -i) iso=1 ;;
    -h) usage ;;
    --) shift; break ;;
    *)
      if [[ "$1" =~ ^-?[0-9]+$ ]]; then
        ts="$1"
      else
        printf 'Error: "%s" is not a valid integer epoch.\n' "$1" >&2
        exit 1
      fi
      ;;
  esac
  shift
done

if [ -z "$ts" ]; then
  printf 'Error: exactly one non-empty epoch integer required.\n' >&2
  usage
fi

tz_flag=""
[ "$utc" -eq 1 ] && tz_flag="-u"

if [ "$iso" -eq 1 ]; then
  if [ "$utc" -eq 1 ]; then
    date $tz_flag -d "@$ts" +"%Y-%m-%dT%H:%M:%SZ"
  else
    date -d "@$ts" +"%Y-%m-%dT%H:%M:%S%z"
  fi
else
  date $tz_flag -d "@$ts"
fi

How to Use It

Save the script as epoch2date, run chmod +x epoch2date, and call it:

# Default: local timezone, human-readable
./epoch2date 1700000000

# Force UTC
./epoch2date -u 1700000000

# ISO 8601 with local offset
./epoch2date -i 1700000000

# ISO 8601, UTC (the format most APIs and log shippers expect)
./epoch2date -u -i 1700000000

# Pre-epoch timestamp
./epoch2date -u -i -1

If you're scripting against this in a pipeline, the -u -i combination gives you a stable, lexicographically sortable string. Pipe it into sort, awk, or feed it directly into a Graylog field extraction rule without worrying about your server's local timezone shifting the output between runs.

That's the whole script. Thirty lines, no external dependencies, and it does the one job correctly.


Luke Keam
Spot a bug or want a custom utility built? I'd love to hear from you. Get in touch
Luke Keam | techgeek.biz