Name
printf — stdin stdout - file -- opt --help --version
Synopsis
printfformat_string
[arguments
]
The printf
command is an
enhanced echo
: it prints formatted
strings on standard output. It operates much like the C programming
language function printf( )
, which
applies a format string to a sequence of arguments to create some
specified output. For example:
➜ printf "User %s is %d years old.\n" sandy 29
User sandy is 29 years old.
The first argument is the format string, which in our example
contains two format specifications, %s
and %d
. The subsequent arguments, sandy and 29,
are substituted by printf
into the
format string and then printed. Format specifications can get fancy
with floating-point numbers:
➜ printf "That\'ll be $%0.2f, sir.\n" 3
That'll be $3.00, sir.
It is your responsibility to make sure the number of format
specifications (%
) equals the
number of arguments supplied to printf
after the format string. If you have
too many arguments, the extras are ignored, and if you have too few,
printf
assumes default values (0
for numeric formats, an empty string for string formats).
Nevertheless, you should treat such mismatches as errors, even though
printf
is forgiving. If they lurk
in your shell scripts, they are bugs waiting to happen.
Format specifications are described in detail on the manpage for the C function
printf
(see man 3
printf
). Here are some useful ones:
| Decimal integer |
| Long decimal integer |
| Octal integer |
| Hexadecimal integer |
| Floating point |
| Double-precision ... |
Get Macintosh Terminal Pocket Guide 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.