printf (Unix)
{{short description|Standard UNIX utility}}
{{lowercase|title=printf}}
{{Refimprove|date=July 2010}}
{{Infobox software
| name = printf
| logo =
| screenshot = Printf-example-command.gif
| screenshot size =
| caption =
| author =
| developer = Various open-source and commercial developers
| released =
| latest release version =
| latest release date =
| operating system = Unix and Unix-like
| platform = Cross-platform
| genre = Command
| license = coreutils: GPLv3+{{Cite web|url=https://linux.die.net/man/1/printf|title=printf(1): format/print data - Linux man page|website=linux.die.net}}
| website =
}}
In Unix and Unix-like operating systems, printf is a shell builtin (and utility program{{Cite web|url=https://www.gnu.org/software/coreutils/manual/coreutils.html#printf-invocation|title=GNU Coreutils|website=www.gnu.org}}) that formats and outputs text like the same-named C function.
Originally named for outputting to a printer, it actually outputs to standard output.{{man|1|printf|Linux}}
The command accepts a format string, which specifies how to format values, and a list of values.
Characters in the format string are copied to the output verbatim except when a format specifier is found which causes a value to be output.
In addition to the standard format specifiers, %b
causes the command to expand backslash escape sequences (for example \n
for newline), and %q
outputs an item that can be used as shell input. The format string is reused if there are more items than format specs. Unused format specs provide a zero value or null string.
History
{{code|printf}} is part of the X/Open Portability Guide since issue 4 of 1992. It was inherited into the first version of POSIX.1 and the Single Unix Specification.{{man|cu|printf|SUS}} It first appeared in 4.3BSD-Reno.{{man|1|printf|FreeBSD}}
The version of printf
bundled in GNU coreutils was written by David MacKenzie. It has an extension {{tt|%q}} for escaping strings in POSIX-shell format.
Examples
{{pre|
{{codett|2=console|$ for NUMBER in 4 6 8 9 10}}
> {{codett|2=bash|do printf " >> %03d %d<< \n" $NUMBER $RANDOM}}
> {{codett|2=bash|done}}
>> 004 26305<<
>> 006 6687<<
>> 008 20170<<
>> 009 28322<<
>> 010 4400<<
}}
This will print a directory listing, emulating 'ls':
{{sxhl|2=console|
$ printf "%s\n" *
}}
See also
- printf, the C function
References
{{Reflist}}