On 2026-11-17, Christian Weisgerber <nad…@mips.inka.de> wrote:
> Any POSIX lawyers around?
I'm supposed to be in court, but it was unexpectedly adjourned.
> Various printf(1) implementations attempt option parsing on the first
> argument and choke on something like "printf ---":
There is a "--" argument which means "this is the last option; only
ordinary non-option arguments follow". Obviously, "---" is not that
argument.
> FreeBSD sh(1) builtin: printf: Illegal option --
> FreeBSD standalone: printf: illegal option -- -
> bash(1) builtin: -bash: printf: --: invalid option
>
> POSIX does not specify any options for printf(1).
However, POSIX does still specify the -- option for printf; it's just
not spelled out in the description of printf.
Contrast this situation with that of the echo utility. For echo,
much more is written than just "OPTIONS ... None":
The echo utility shall not recognize the "--" argument in the manner
specified by Guideline 10 of XBD 12.2 Utility Syntax Guidelines; "--"
shall be recognized as a string operand.
Implementations shall not support any options.
The printf utility is in no way similarly excused from supporting --,
nor forbidden from having options courtesy of the implementor.
(Implementations of echo, such as the Bash builtin and the coreutils
echo, ignore the proscription against supporting options.)
> The workaround is to explicitly terminate option parsing with "--",
> i.e., "printf -- ---". That works at least across OpenBSD, FreeBSD,
> GNU coreutils and bash. But does it conform to POSIX?
I believe yes; though POSIX does not specify any required options
for printf, the utility conforms to the common guidelines.
The description of printf itself has a FUTURE DIRECTIONS section where
it is spelled out that implementations can add options:
A future version of this standard is expected to add a %b conversion to
the printf() function for binary conversion of integers, in alignment
with the next version of the ISO C standard. This will result in an
inconsistency between the printf utility and printf() function for
format strings containing %b. Implementors are encouraged to collaborate
on a way to address this which could then be adopted in a future version
of this standard. For example, the printf utility could add a -C option
to make the format string behave in the same way, as far as possible, as
the printf() function.
printf is allowed to treat arguments that start with - as options,
and diagnose nonexistent options.
Highly portable scripts must take care not to use format strings
that start with -.
Also, do not pass the expansion of a variable to printf:
printf "$TEXT\n" # no
printf "%s\n" "$TEXT" # yes
--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @Kazi…@mstdn.ca