diff mbox series

builtin: diagnose attempt to printf '' as number

Message ID 20241119193211.1585716-1-eggert@cs.ucla.edu (mailing list archive)
State Under Review
Delegated to: Herbert Xu
Headers show
Series builtin: diagnose attempt to printf '' as number | expand

Commit Message

Paul Eggert Nov. 19, 2024, 7:31 p.m. UTC
Fix "printf %d ''" to issue a diagnostic and exit nonzero, as
done by traditional printf and as required by POSIX.  See
https://pubs.opengroup.org/onlinepubs/9799919799/utilities/printf.html
which says "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".

GNU coreutils has already been patched to do the same thing.
I plan to send in a patch to GNU Bash shortly.
---
 ChangeLog          |  4 ++++
 src/bltin/printf.c | 10 +++++-----
 2 files changed, 9 insertions(+), 5 deletions(-)
diff mbox series

Patch

diff --git a/ChangeLog b/ChangeLog
index 406e20c..4c16886 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,7 @@ 
+2024-11-19  Paul Eggert <eggert@cs.ucla.edu>
+
+	* printf now diagnoses attempts to treat empty strings as numbers.
+
 2014-11-17  Stéphane Aulery <saulery@free.fr>
 
 	* Correct typo in manual page.
diff --git a/src/bltin/printf.c b/src/bltin/printf.c
index 46c6295..11fcefa 100644
--- a/src/bltin/printf.c
+++ b/src/bltin/printf.c
@@ -540,11 +540,11 @@  getdouble(void)
 static void
 check_conversion(const char *s, const char *ep)
 {
-	if (*ep) {
-		if (ep == s)
-			warnx("%s: expected numeric value", s);
-		else
-			warnx("%s: not completely converted", s);
+	if (ep == s) {
+		warnx("%s: expected numeric value", s);
+		rval = 1;
+	} else if (*ep) {
+		warnx("%s: not completely converted", s);
 		rval = 1;
 	} else if (errno == ERANGE) {
 		warnx("%s: %s", s, strerror(ERANGE));