printf

The printf command, available in bash since version 2.02, has two parts (beyond the command name): a format string and a variable number of arguments:

printfformat-string [arguments]

format-string describes the format specifications; this is best supplied as a string constant in quotes. arguments is a list, such as a list of strings or variable values that correspond to the format specifications.

The format is reused as necessary to use up all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied.

A format specification is preceded by a percent sign (%), and the specifier is one of the characters described below. Two of the main format specifiers are %s for strings and %d for decimal integers (see Table A-13).

Table A-13. printf format specifiers

Format character

Meaning

%c

ASCII character (prints first character of corresponding argument)

%d, %i

Decimal (base 10) integer

%e

Floating-point format ([-]d.precisione[+-]dd)—see the text after the table for the meaning of precision

%E

Floating-point format ([-]d.precisionE[+-]dd)

%f

Floating-point format ([-]ddd.precision)

%g

%e or %f conversion, whichever is shorter, with trailing zeros removed

%G

%E or %f conversion, whichever is shortest, with trailing zeros removed

%o

Unsigned octal value

%s

String

%u

Unsigned decimal value

%x

Unsigned hexadecimal number; uses a-f for 10 to 15

%X

Unsigned hexadecimal number; ...

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.