Skip to content
Tutorials Center
My learning

Topics

Lesson 60 of 95 ยท Advanced Bash

printf, Dates and Formatting

Master printf formats, padding and columns, %q quoting, printf -v and %(fmt)T, GNU date with epoch seconds and time zones, sorting dates and computing durations in Bash.

Output formatting and dates look like small topics until a script prints a misaligned report, drifts by an hour when daylight saving starts, or fails on printf '%d' 08. This lesson covers the two tools that handle almost all of it: printf, the precise replacement for echo, and date, together with Bash's own time formatter %(fmt)T that avoids starting a process at all.

A rule that keeps date code reproducible: never trust the current time in an example or a test. Convert from a fixed Unix timestamp (date -d @1700000000), set the time zone explicitly (TZ=UTC), and your output is identical on every machine and every run. That is how every example here works.

printf in depth

printf FORMAT [ARGUMENT]... prints the format, replacing each % conversion with the next argument. It does not add a trailing newline (write \n), it interprets backslash escapes in the format only, and its behaviour is the same on every system, which echo -e is not (see Creating and Viewing Files).

The most important quirk: the format is reused until the arguments run out.

Bash Formats are reused for extra arguments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Never pass untrusted text as the format (printf "$user_input"): % sequences and backslashes in it would be interpreted. Always write printf '%s\n' "$user_input".

The conversions

Conversion Meaning Example
%s string printf '%s' abc
%d %i signed decimal integer printf '%d' 42
%u unsigned integer printf '%u' 5
%x %X hexadecimal (lower, upper) 255 gives ff / FF
%o octal 8 gives 10
%f %e %g floating point: fixed, exponent, shortest printf '%.2f' 3.14159
%c the first character of the argument printf '%c' hello prints h
%b string with backslash escapes interpreted printf '%b' 'a\tb'
%q the string quoted so the shell can read it back see below
%% a literal percent sign
%(fmt)T a time (Bash only), see below

Between the % and the letter you can put flags, a width and a precision: %-8s (left-aligned in 8 columns), %08.3f (zero-padded, width 8, 3 decimals), %+d (always show the sign), %#x (add the 0x prefix), %.3s (at most 3 characters), %*d (width taken from an argument).

Bash Flags, width and precision

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Numbers: the traps

printf is strict about numbers, and one rule surprises almost everyone: a leading zero means octal. 08 and 09 are not valid octal, and floating point values are not accepted by %d:

Bash printf and numbers that look like numbers (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The first command prints 8 and 31. The second reports invalid octal number on stderr and prints 0, and the third reports invalid number yet still prints 3. The standard cure for zero-padded input such as months or hours is 10#, which forces base ten in arithmetic: $((10#$month)).

Building tables

For a table, decide column widths once and reuse one format string. Measuring the widest value first makes the table fit any data:

Bash A report with computed column widths

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Here, printf "$fmt" is fine because we built the format. A line of dashes without a loop is printf '%*s' N '' | tr ' ' '-': print N spaces, then translate them.

In Bash 5.0, %s widths count bytes, not characters. Columns that contain accents, CJK text or emoji come out crooked: printf '[%5s]' รฉ pads with three spaces, not four. For such data use awk, or pad by hand using ${#var} (which does count characters in a UTF-8 locale).

%q, %b and escaping

%q quotes an argument so the shell reads it back as the same single word. It is the right tool for building commands to run later or elsewhere (for example the second parse in SSH, scp and Working Remotely) and for logging values that may contain spaces or newlines unambiguously. %b goes the other way and interprets escapes such as \t in an argument (a format would do it anyway).

Bash %q and %b round trips

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

printf -v: format into a variable

printf -v name FORMAT ... stores the result in a variable instead of printing it. It does the same as name=$(printf ...) but without the subshell, so it is faster in loops and does not strip trailing newlines.

Terminal
printf -v padded '%05d' 42      # padded=00042
printf -v "line_$i" '%s' "$x"   # assign to a computed name (no eval needed)

Time without a process: %(fmt)T

Bash can format a timestamp itself. printf '%(FORMAT)T' SECONDS uses the same format codes as date (they are the C library's strftime codes). Special arguments: -1 means "now" and -2 means "when this shell started". Bash 5.0 also provides $EPOCHSECONDS (integer) and $EPOCHREALTIME (microseconds, with a decimal point), so you rarely need date for the current time.

Bash Bash's built-in time formatting

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

In a script that logs thousands of lines, printf '%(...)T' -1 avoids thousands of forks (see Performance, Tricks and Pitfalls). Inside the function above we pass a fixed time only so that the output of this lesson is repeatable.

GNU date

date prints or converts times. The big three uses are: format the current or a given time (+FORMAT), convert between text and epoch seconds (-d), and do calendar arithmetic with relative expressions. All of the following assume GNU date (Linux); macOS and BSD differ, see the note after.

The formats you will reach for:

Code Result Code Result
%F 2023-11-14 (same as %Y-%m-%d) %T 22:13:20 (%H:%M:%S)
%Y %m %d year, month, day %H %M %S hour (00-23), minute, second
%s seconds since 1970-01-01 UTC %N nanoseconds (GNU only)
%a %A Tue / Tuesday %b %B Nov / November
%j day of year (001-366) %u weekday 1-7 (Monday is 1)
%U week of year (Sunday as first day) %Z %z zone name / offset
%e day, space-padded %-d day without padding (GNU flag)
Bash Formatting one instant many ways

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Arithmetic on dates

GNU date -d understands phrases like +10 days, -1 month, tomorrow, last day, relative to a base date you provide:

Bash Calendar arithmetic with date -d

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The +1 month trap is real: 2026-01-31 +1 month is "February 31st", which GNU date normalises to 3 March. Calendar arithmetic around month ends is where date bugs hide. Compute from the first of the month, or from the middle, and test around the 29th to 31st.

Durations

To measure the gap between two moments, convert both to epoch seconds, subtract, and format the difference yourself. Epoch seconds ignore time zones and daylight saving, which is what makes this reliable.

Bash Differences between two moments

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The calendar: cal and ncal

On many systems the cal command (from util-linux, or bsdmainutils on Debian) prints a month calendar. The sandbox does not ship it, so these are read-only; the next example builds the same output yourself.

CONSOLE
$ cal                    # the current month, today highlighted
$ cal 2 2024             # February 2024
$ cal 2024               # the whole year
$ cal -3                 # previous, current and next month
$ cal -y                 # the current year
$ cal -m                 # weeks start on Monday (-s starts on Sunday)
$ cal -j                 # Julian days: day numbers counted from January 1st
$ ncal 2 2024            # ncal turns the month on its side: one row per weekday
$ ncal -b 2 2024         # -b: the classic cal layout

Two historical notes. cal uses the Gregorian calendar (leap years are divisible by 4, except centuries, except those divisible by 400) for all dates in modern use. On some systems cal 9 1752 shows the month when Britain and its colonies dropped eleven days to switch from the Julian calendar to the Gregorian one. The Julian calendar has a leap year every four years without exceptions, which drifts by about three days every four centuries.

You can print a month with date and some arithmetic: ask for the weekday of the first day (%w) and the number of days in the month, then pad.

Bash A calendar in 12 lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

Time zones and daylight saving

The rule that makes all of this tractable: store and compare instants in UTC (epoch seconds); convert to a zone only when showing a time to a person. The TZ variable selects the zone for a single command. Zone names come from the IANA database (Europe/Berlin, Asia/Tokyo, America/New_York); avoid abbreviations such as EST in scripts, since they are ambiguous.

Bash One instant, several zones, and a 23-hour day

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

The last loop shows why epoch / 86400 is "number of days" only for UTC. In a DST zone a "day" is 23 or 25 hours twice a year; compute calendar differences in UTC, and use zone-aware arithmetic (date -d "... +1 day") when you mean "same wall-clock time tomorrow". Servers should run in UTC; cron and users' displays are where zones belong.

Sorting dates

ISO 8601 dates (2026-03-14, 2026-03-14T09:15:00Z) sort correctly as plain text, which is the main reason to use them in log files and file names. Other formats need help:

Bash Sorting dates in other formats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with read or cat), it gets the next line from this box.

(That is the "decorate, sort, undecorate" pattern; see sort, uniq, cut, tr and wc.)

GNU versus BSD and macOS

date is one of the least portable commands. GNU date -d STRING does not exist on macOS/BSD; there the same jobs need different flags. The only parts that are the same everywhere are date +FORMAT with the common % codes and date +%s for the current epoch time.

Task GNU (Linux) BSD / macOS
Epoch to text date -d @1700000000 date -r 1700000000
Text to epoch date -d '2026-03-14' +%s date -j -f '%Y-%m-%d' 2026-03-14 +%s
Add 10 days date -d '+10 days' date -v+10d
%N, %-d, %^a supported mostly not

Scripts that must run on both can test for GNU (date --version >/dev/null 2>&1) and branch, use printf '%(...)T' (Bash), or install GNU coreutils on the Mac (gdate). More on this in POSIX sh, Portability and Compatibility.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does printf '%s-%s\n' a b c print?

    The format is reused until the arguments run out. The second round has only one argument, so the missing %s becomes an empty string and prints c-.
  2. 2. Why does printf '%d' 08 print an error?

    Like in C, 0 introduces octal. Use $((10#08)) to force base ten, or strip the zero.
  3. 3. What is the main benefit of printf '%(%F %T)T' -1 over $(date '+%F %T')?

    The %(fmt)T conversion is built into Bash 4.2+ and the -1 argument means now. No fork or exec is needed, which matters in loops.
  4. 4. What does date -d '2026-01-31 +1 month' +%F print with GNU date?

    February 31 does not exist, so GNU date normalises it by overflowing into March: 28 days in February, so day 31 becomes March 3.
  5. 5. Which approach is the most reliable way to compute how long ago a log timestamp was?

    Epoch seconds are a single number that ignores time zones and daylight saving, so subtraction gives the true elapsed time.

Summary

  • printf reuses its format for extra arguments, never adds a newline, and should never receive untrusted text as the format; use printf '%s\n' "$text".
  • Conversions: %s %d %x %o %f %e %c %b %q %%; flags and widths such as %-10s, %05d, %+d, %.2f, %*s build aligned tables. Leading zeros mean octal: use 10#08.
  • In Bash 5.0, %s widths count bytes, so non-ASCII text misaligns.
  • %q and ${var@Q} quote values for re-use; printf -v var ... formats into a variable without a subshell.
  • printf '%(%F %T)T' -1, $EPOCHSECONDS and $EPOCHREALTIME give time without date.
  • GNU date -d converts text and epoch values and does relative arithmetic (beware +1 month at month ends); use TZ=UTC and fixed timestamps for reproducible output.
  • Store and compare times as UTC epoch seconds, convert to a zone only for display, and remember DST days have 23 or 25 hours.
  • ISO 8601 dates sort as text; other formats need keys, sort -M, or conversion to epoch first. BSD/macOS date has different flags.

Next: POSIX sh, Portability and Compatibility