Printf (Unix)
- 1 min read
- 2 chapters
Related on Lably
Through Operating system, Computer program and Printer (computing)
Originally named for outputting to a printer, it actually outputs to standard output.
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
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. It first appeared in 4.3BSD-Reno.
The version of printf bundled in GNU coreutils was written by David MacKenzie. It has an extension %q for escaping strings in POSIX-shell format.
Sign in to keep reading
One more chapter is free with a Lably account.
Examples
<syntaxhighlight lang="console" class="" style="background:none; border:none; color:inherit; padding: 0px 0px;" inline="1">$ for NUMBER in 4 6 8 9 10</syntaxhighlight> > <syntaxhighlight lang="bash" class="" style="background:none; border:none; color:inherit; padding: 0px 0px;" inline="1">do printf " >> %03d %d<< \n" $NUMBER $RANDOM</syntaxhighlight> > <syntaxhighlight lang="bash" class="" style="background:none; border:none; color:inherit; padding: 0px 0px;" inline="1">done</syntaxhighlight> >> 004 26305<< >> 006 6687<< >> 008 20170<< >> 009 28322<< >> 010 4400<<
This will print a directory listing, emulating 'ls':
<span id="mwQw"></span><span class="gp" id="mwRA">$ </span><span class="nb" id="mwRQ">printf</span><span class="w" id="mwRg"> </span><span class="s2" id="mwRw">"%s\n"</span><span class="w" id="mwSA"> </span>*

