PRINTF(1P)

๐ŸŒธ PROLOG ๐ŸŒธ

Okay bestie, real talk before we even start: this manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ โ€” so go check the corresponding Linux manual page if you want the Linux-specific deets โ€” or honestly, the interface might not even be implemented on Linux at all. ๐Ÿ’€

So this is the PRINTF(1P) page, and yes, the 1P means it lives in the POSIX Programmer's Manual section of the man pages. Slay.


๐Ÿ’– NAME ๐Ÿ’–

printf โ€” write formatted output โœจ


๐ŸŽ€ SYNOPSIS ๐ŸŽ€

printf format [argument...]

๐Ÿฆ‹ DESCRIPTION ๐Ÿฆ‹

So the printf utility shall write formatted operands to the standard output. That's the whole vibe. ๐ŸŒˆ

The argument operands shall be formatted under the control of the format operand. The format is the boss, the arguments are the entourage. ๐Ÿ‘‘


โœจ OPTIONS โœจ

None. Literally none. Not a single flag. Zero options, zero notes, she simply doesn't need them. ๐Ÿ’…


๐Ÿ“ OPERANDS ๐Ÿ“

The following operands shall be supported:

  • format โ€” a string describing the format to use to write the remaining operands. See the EXTENDED DESCRIPTION section, because that's where all the juicy stuff lives. ๐Ÿ‘€
  • argument โ€” the strings to be written to standard output, under the control of format. See the EXTENDED DESCRIPTION section too. ๐Ÿ’œ

๐Ÿ™ˆ STDIN ๐Ÿ™ˆ

Not used. She does not read from stdin. She only speaks. ๐Ÿ“ข


๐Ÿ“ INPUT FILES ๐Ÿ“

None. Nothing gets opened. Nothing gets read. Peace and quiet. โœŒ๏ธ


๐ŸŒ ENVIRONMENT VARIABLES ๐ŸŒ

The following environment variables shall affect the execution of printf:

  • LANG โ€” provide a default value for the internationalization variables that are unset or null. (See the Base Definitions volume of POSIX.1โ€2017, Section 8.2, Internationalization Variables, for the precedence of internationalization variables used to determine the values of locale categories.)
  • LC_ALL โ€” if set to a non-empty string value, override the values of all the other internationalization variables. She's the main character and she overrides everyone. ๐Ÿ‘‘
  • LC_CTYPE โ€” determine the locale for the interpretation of sequences of bytes of text data as characters (for example, single-byte as opposed to multi-byte characters in arguments).
  • LC_MESSAGES โ€” determine the locale that should be used to affect the format and contents of diagnostic messages written to standard error.
  • LC_NUMERIC โ€” determine the locale for numeric formatting. It shall affect the format of numbers written using the e, E, f, g, and G conversion specifier characters (if supported).
  • NLSPATH โ€” determine the location of message catalogs for the processing of LC_MESSAGES.

โšก ASYNCHRONOUS EVENTS โšก

Default. Nothing special, nothing extra, just the usual behavior. ๐Ÿซถ


๐Ÿ’Œ STDOUT ๐Ÿ’Œ

See the EXTENDED DESCRIPTION section. That's where the formatting lore is. ๐Ÿ“–


๐Ÿ˜ญ STDERR ๐Ÿ˜ญ

The standard error shall be used only for diagnostic messages. She keeps her feelings in stderr, respectfully. ๐Ÿ’€


๐Ÿ—‚๏ธ OUTPUT FILES ๐Ÿ—‚๏ธ

None. She writes to stdout and stderr and that's it, no files, no side quests. โœจ


๐Ÿงš EXTENDED DESCRIPTION ๐Ÿงš

Okay bestie, this is the part where it gets good. The format operand shall be used as the format string described in the Base Definitions volume of POSIX.1โ€2017, Chapter 5, File Format Notation โ€” with the following exceptions:

  1. A <space> in the format string, in any context other than a flag of a conversion specification, shall be treated as an ordinary character that is copied to the output.
  2. A '' character in the format string shall be treated as a '' character, not as a <space>.
  3. In addition to the escape sequences shown in the Base Definitions volume of POSIX.1โ€2017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'), "\ddd", where ddd is a one, two, or three-digit octal number, shall be written as a byte with the numeric value specified by the octal number.
  4. The implementation shall not precede or follow output from the d or u conversion specifiers with <blank> characters not specified by the format operand.
  5. The implementation shall not precede output from the o conversion specifier with zeros not specified by the format operand.
  6. The a, A, e, E, f, F, g, and G conversion specifiers need not be supported. (I know. Tragic. ๐Ÿ˜ญ)
  7. An additional conversion specifier character, b, shall be supported as follows. The argument shall be taken to be a string that can contain <backslash>-escape sequences. The following <backslash>-escape sequences shall be supported:
    • The escape sequences listed in the Base Definitions volume of POSIX.1โ€2017, Chapter 5, File Format Notation ('\\', '\a', '\b', '\f', '\n', '\r', '\t', '\v'), which shall be converted to the characters they represent
    • "\0ddd", where ddd is a zero, one, two, or three-digit octal number that shall be converted to a byte with the numeric value specified by the octal number
    • '\c', which shall not be written and shall cause printf to ignore any remaining characters in the string operand containing it, any remaining string operands, and any additional characters in the format operand

The interpretation of a <backslash> followed by any other sequence of characters is unspecified.

Bytes from the converted string shall be written until the end of the string or the number of bytes indicated by the precision specification is reached. If the precision is omitted, it shall be taken to be infinite, so all bytes up to the end of the converted string shall be written.

  1. For each conversion specification that consumes an argument, the next argument operand shall be evaluated and converted to the appropriate type for the conversion as specified below.
  2. The format operand shall be reused as often as necessary to satisfy the argument operands. Any extra b, c, or s conversion specifiers shall be evaluated as if a null string argument were supplied; other extra conversion specifications shall be evaluated as if a zero argument were supplied. If the format operand contains no conversion specifications and argument operands are present, the results are unspecified.
  3. If a character sequence in the format operand begins with a '%' character, but does not form a valid conversion specification, the behavior is unspecified.
  4. The argument to the c conversion specifier can be a string containing zero or more bytes. If it contains one or more bytes, the first byte shall be written and any additional bytes shall be ignored. If the argument is an empty string, it is unspecified whether nothing is written or a null byte is written.

The argument operands shall be treated as strings if the corresponding conversion specifier is b, c, or s, and shall be evaluated as if by the strtod() function if the corresponding conversion specifier is a, A, e, E, f, F, g, or G. Otherwise, they shall be evaluated as unsuffixed C integer constants, as described by the ISO C standard, with the following extensions:

  • A leading <plus-sign> or <hyphen-minus> shall be allowed.
  • If the leading character is a single-quote or double-quote, the value shall be the numeric value in the underlying codeset of the character following the single-quote or double-quote.
  • Suffixed integer constants may be allowed.

If an argument operand cannot be completely converted into an internal value appropriate to the corresponding conversion specification, a diagnostic message shall be written to standard error and the utility shall not exit with a zero exit status, but shall continue processing any remaining operands and shall write the value accumulated at the time the error was detected to standard output.

It shall not be considered an error if an argument operand is not completely used for a b, c, or s conversion. So like, leftover bytes there? Not a problem. We move on. ๐Ÿ’…

๐Ÿšช EXIT STATUS ๐Ÿšช

The following exit values shall be returned:

  • 0 โ€” successful completion. โœจ
  • >0 โ€” an error occurred. ๐Ÿ’€

๐Ÿ”ฅ CONSEQUENCES OF ERRORS ๐Ÿ”ฅ

Default.

The following sections are informative.


๐ŸŽ€ APPLICATION USAGE ๐ŸŽ€

So, the floating-point formatting conversion specifications of printf() are not required โ€” because all arithmetic in the shell is integer arithmetic. That's the whole reason, no cap. ๐Ÿงฎ

The awk utility performs floating-point calculations and provides its own printf function. The bc utility can perform arbitrary-precision floating-point arithmetic, but does not provide extensive formatting capabilities. (This printf utility cannot really be used to format bc output; it does not support arbitrary precision.) Implementations are encouraged to support the floating-point conversions as an extension.

Note that this printf utility, like the printf() function defined in the System Interfaces volume of POSIX.1โ€2017 on which it is based, makes no special provision for dealing with multi-byte characters when using the %c conversion specification or when a precision is specified in a %b or %s conversion specification. Applications should be extremely cautious using either of these features when there are multi-byte characters in the character set. ๐Ÿ˜ฌ

No provision is made in this volume of POSIX.1โ€2017 which allows field widths and precisions to be specified as '*' since the '*' can be replaced directly in the format operand using shell variable substitution. Implementations can also provide this feature as an extension if they so choose.

Hexadecimal character constants as defined in the ISO C standard are not recognized in the format operand because there is no consistent way to detect the end of the constant. Octal character constants are limited to, at most, three octal digits, but hexadecimal character constants are only terminated by a non-hex-digit character. In the ISO C standard, the "##" concatenation operator can be used to terminate a constant and follow it with a hexadecimal character to be written. In the shell, concatenation occurs before the printf utility has a chance to parse the end of the hexadecimal constant. ๐Ÿ˜ตโ€๐Ÿ’ซ

The %b conversion specification is not part of the ISO C standard; it has been added here as a portable way to process <backslash>-escapes expanded in string operands as provided by the echo utility. See also the APPLICATION USAGE section of echo for ways to use printf as a replacement for all of the traditional versions of the echo utility.

If an argument cannot be parsed correctly for the corresponding conversion specification, the printf utility is required to report an error. Thus, overflow and extraneous characters at the end of an argument being used for a numeric conversion shall be reported as errors. โš ๏ธ


bestie this is only part 1 โ€” hold on, more is coming ๐Ÿ’–

๐ŸŒธ EXAMPLES ๐ŸŒธ

Ok bestie, this is the part where it stops being theory and starts being useful. Let's go. ๐Ÿ’…

Example the first โ€” to alert the user and then print and read a series of prompts:

printf "\aPlease fill in the following: \nName: "
read name
printf "Phone number: "
read phone

See how it alerts the user first (that's the whole point of doing it this way), and then prints and reads the prompts? Iconic behaviour honestly. โœจ


Example the second โ€” to read out a list of right and wrong answers from a file, calculate the percentage correctly, and print them out. The numbers are right-justified and separated by a single <tab>. The percentage is written to one decimal place of accuracy:

while read right wrong ; do
    percent=$(echo "scale=1;($right*100)/($right+$wrong)" | bc)
    printf "%2d right\t%2d wrong\t(%s%%)\n" \
        $right $wrong $percent
done < database_file

Look at that <tab> doing its little job and the percentage hitting exactly one decimal place. No notes. ๐ŸŽ€


Example the third โ€” the command:

printf "%5d%4d\n" 1 21 321 4321 54321

produces:

    1  21
  3214321
54321   0

Now clock this, because it's the whole โœจvibeโœจ of printf: the format operand got used three times to print all of the given strings, and a '0' was supplied by printf to satisfy the last %4d conversion specification. It just... kept going. Main character energy. ๐Ÿ’–


Example the fourth โ€” the printf utility is required to notify the user when conversion errors are detected while producing numeric output. So on an implementation with 32-bit twos-complement integers, when %d is specified as the format operand, these are the results you'd expect:

  • Argument 5a โ€” Standard Output: 5 โ€” Diagnostic Output: printf: "5a" not completely converted
  • Argument 9999999999 โ€” Standard Output: 2147483647 โ€” Diagnostic Output: printf: "9999999999" arithmetic overflow
  • Argument -9999999999 โ€” Standard Output: -2147483648 โ€” Diagnostic Output: printf: "-9999999999" arithmetic overflow
  • Argument ABC โ€” Standard Output: 0 โ€” Diagnostic Output: printf: "ABC" expected numeric value

The diagnostic message format is not specified, but these examples convey the type of information that should be reported. Note that the value shown on standard output is what would be expected as the return value from the strtol() function as defined in the System Interfaces volume of POSIX.1โ€2017. A similar correspondence exists between %u and strtoul() and %e, %f, and %g (if the implementation supports floating-point conversions) and strtod(). ๐Ÿงš


Example the fifth โ€” in a locale using the ISO/IEC 646:1991 standard as the underlying codeset, the command:

printf "%d\n" 3 +3 -3 \'3 \"+3 "'-3"

produces:

3     Numeric value of constant 3

3     Numeric value of constant 3

-3    Numeric value of constant -3

51    Numeric value of the character '3' in the ISO/IEC 646:1991 standard codeset

43    Numeric value of the character '+' in the ISO/IEC 646:1991 standard codeset

45    Numeric value of the character '-' in the ISO/IEC 646:1991 standard codeset

Look at all those little escapes doing their thing. The leading \' and \" and the sneaky "'-3" all pulling their weight. ๐Ÿฆ‹

Note that in a locale with multi-byte characters, the value of a character is intended to be the value of the equivalent of the wchar_t representation of the character as described in the System Interfaces volume of POSIX.1โ€2017.


๐Ÿ‘‘ RATIONALE ๐Ÿ‘‘

So, the tea โ˜•: the printf utility was added to provide functionality that has historically been provided by echo. However, due to irreconcilable differences in the various versions of echo extant, that version has few special features, leaving those to this new printf utility, which is based on one in the Ninth Edition system. echo was messy, printf showed up and fixed it. Periodt. ๐Ÿ’…

The EXTENDED DESCRIPTION section almost exactly matches the printf() function in the ISO C standard, although it is described in terms of the file format notation in the Base Definitions volume of POSIX.1โ€2017, Chapter 5, File Format Notation. So like, same energy, different framing. โœจ

Earlier versions of this standard specified that arguments for all conversions other than b, c, and s were evaluated in the same way (as C constants, but with stated exceptions). For implementations supporting the floating-point conversions it was not clear whether:

  • integer conversions need only accept integer constants and floating-point conversions need only accept floating-point constants, or
  • whether both types of conversions should accept both types of constants.

Also, by not distinguishing between them, the requirement relating to a leading single-quote or double-quote applied to floating-point conversions even though this provided no useful functionality to applications that was not already available through the integer conversions. Messy. ๐Ÿ™ˆ

The current standard clarifies the situation by specifying that:

  • the arguments for floating-point conversions are evaluated as if by strtod(), and
  • the arguments for integer conversions are evaluated as C integer constants,

with the special treatment of leading single-quote and double-quote applying only to integer conversions. Clear as a fresh glass of strawberry milk. ๐Ÿ“


๐ŸŒˆ FUTURE DIRECTIONS ๐ŸŒˆ

None.

(That's it. That's the section. Slay, honestly. ๐Ÿ’€)


๐Ÿ”ฅ SEE ALSO ๐Ÿ”ฅ

  • awk
  • bc
  • echo

The Base Definitions volume of POSIX.1โ€2017, Chapter 5, File Format Notation, Chapter 8, Environment Variables

The System Interfaces volume of POSIX.1โ€2017, fprintf(), strtod()


Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1-2017, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, 2018 Edition, Copyright (C) 2018 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.opengroup.org/unix/online.html .

Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .


And that's the whole page, bestie!! ๐Ÿซถ This one came to you from IEEE/The Open Group, dated 2017, and it's the PRINTF(1P) page โ€” so if you ever need to cite it, that's your source and your year. Go forth and format things flawlessly. ๐Ÿ’–โœจ๐ŸŽ€

๐Ÿ“ฆ where this page comes from