Date: Fri, 17 Apr 2020 16:12:20 -0400
From: Chet Ramey <[email protected]>
Message-ID: <[email protected]>
| I would say this is a programmer error. The way precisions work with
| string arguments is that the argument is fetched or generated (this
| includes generating the quoted string for %q or the expanded string for
| %b) and then printf writes number of bytes (!) from that generated string
| specified by the precision.
This happens only because of the cheap way we (and I presume you)
implement things - in any rational scheme, it would take the precision
chars from the source string, and then quote them.
But that's hard - instead we just use printf to do the work, %q quotes
the arg string, and then the 'q' is changed to a 's' in the format, and
we just call printf(3) to do the work (padding, justification, ...)
The only excuse for this is pragmatics, no-one would deliberately set
out to design something quite that bogus.
The end result is as Greg said, "Don't do that", if precisions are
needed with %q do something like
printf 'echo %q%q\n' "$(printf %.2s "a'b")" ';ls'
which produces
echo a\'\;ls
which I expect is the desired result.
kre