Writing Output with More Formatting Control

Problem

You want more control over the formatting and placement of output.

Solution

Use the printf built-in command.

For example:

$ printf '%s = %d\n' Lines $LINES
Lines = 24
$

or:

$ printf '%-10.10s = %4.2f\n' 'GigaHerz' 1.92735
GigaHerz   = 1.93
$

Discussion

The printf built-in command behaves like the C language library call, where the first argument is the format control string and the successive arguments are formatted according to the format specifications (%).

The numbers between the % and the format type (s or f in our example) provide additional formatting details. For the floating-point type (f), the first number (4 in the 4.2 specifier) is the width of the entire field. The second number (2) is how many digits should be printed to the right of the decimal point. Note that it rounds the answer.

For a string, the first digit is the maximum field width, and the second is the minimum field width. The string will be truncated (if longer than max) or blank padded (if less than min) as needed. When the max and min specifiers are the same, then the string is guaranteed to be that length. The negative sign on the specifier means to left align the string (within its field width). Without the minus sign, the string would right justify, thus:

$ printf '%10.10s = %4.2f\n' 'GigaHerz' 1.92735
GigaHerz =   1.93
$

The string argument can either be quoted or unquoted. Use quotes if you need to preserve embedded spacing (there were no spaces needed in our one-word ...

Get bash Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.