bug-bash
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

printf %n is not documented


From: Emanuele Torre
Subject: printf %n is not documented
Date: Fri, 23 Dec 2022 13:24:59 +0100

About two months ago, I discovered, reading the bash source code for
printf, the %n format specifier.

What it does is assign to the variable specified as its argument, the
number of bytes that have been written so far (similarly to the C
counterpart).

This can be quite useful if you, for example, want to compute byte
length of a string:

  printf -v _ %s%n "$str" str_bytelength

Without %n, you would have to temporarily change the locale to C, and
use ${#str}; e.g. like so:

  LC_CTYPE=C command eval 'str_bytelength=${#str}'

This feature is not officially documented by bash. But it was introduced
in bash 2.05a, and it was mentioned in the changelog:

https://lists.gnu.org/archive/html/bug-bash/2001-11/msg00086.html

> c.  The `printf' builtin now handles the %n conversion like printf(3).
>     The corresponding argument is the name of a shell variable to which the
>     value is assigned.

It seems that ksh93 also supports this feature, but it does not document
it either.

Since this feature has been in bash for over 20 years, it was mentioned
in the changelog of the release in which it was introduced, and it has
that useful use case of computing the byte length of a variable without
having to temporarily set the locale to C, could it be officially
documented in bash's documentation?

 emanuele6



reply via email to

[Prev in Thread] Current Thread [Next in Thread]