Configuration Information [Automatically generated, do not change]:
Machine: x86_64
OS: linux-gnu
Compiler: gcc -std=gnu23
Compilation CFLAGS: -g -O2
uname output: Linux penguin.cs.ucla.edu 6.11.6-200.fc40.x86_64 #1 SMP PREEMPT_DYNAMIC Fri Nov 1 16:09:34 UTC 2024 x86_64 GNU/Linux
Machine Type: x86_64-pc-linux-gnu

Bash Version: 5.3
Patch Level: 0
Release Status: beta

Description:

printf doesn't diagnose attempts to print empty strings as numbers. This doesn't conform to POSIX and disagrees with the traditional Unix printf command.

Repeat-By:

printf %d ''

This should behave like "printf %d ' '", and should output a diagnostic and exit with status 1; instead it silently exits with status 0.

Fix:
Attached.
From f2583bf297268c08b474c68b0a8a2188f8d555cf Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Tue, 19 Nov 2024 11:35:21 -0800
Subject: [PATCH] diagnose attempts to printf '' as a number

---
 builtins/printf.def | 4 ++--
 tests/printf.right  | 8 ++++++++
 tests/printf.tests  | 5 +++++
 3 files changed, 15 insertions(+), 2 deletions(-)

diff --git a/builtins/printf.def b/builtins/printf.def
index d7fc8f87..afe5cf7d 100644
--- a/builtins/printf.def
+++ b/builtins/printf.def
@@ -1374,7 +1374,7 @@ getint (int overflow_retval)
   ret = strtoimax (garglist->word->word, &ep, 0);
   overflow = (errno == ERANGE) || (ret < INT_MIN || ret > INT_MAX);
 
-  if (*ep)
+  if (*ep || ep == garglist->word->word)
     {
       sh_invalidnum (garglist->word->word);
       conversion_error = 1;
@@ -1401,7 +1401,7 @@ getintmax (void)
   errno = 0;
   ret = strtoimax (garglist->word->word, &ep, 0);
 
-  if (*ep)
+  if (*ep || ep == garglist->word->word)
     {
       sh_invalidnum (garglist->word->word);
       /* POSIX.2 says ``...a diagnostic message shall be written to standard
diff --git a/tests/printf.right b/tests/printf.right
index 7c2e19a5..1e274c5d 100644
--- a/tests/printf.right
+++ b/tests/printf.right
@@ -169,6 +169,14 @@ xx
 9223372036854775807
 ./printf.tests: line 365: printf: -9223372036854775815: Result too large
 -9223372036854775808
+./printf.tests: line 367: printf: : invalid number
+0
+./printf.tests: line 368: printf:  : invalid number
+0
+./printf.tests: line 369: printf: : invalid number
+        30
+./printf.tests: line 370: printf: : invalid number
+0000000030
 	one
 one\ctwo
 4\.2
diff --git a/tests/printf.tests b/tests/printf.tests
index af03960a..27ffcef2 100644
--- a/tests/printf.tests
+++ b/tests/printf.tests
@@ -364,6 +364,11 @@ TOOSMALL=-9223372036854775815
 printf '%d\n' "$TOOBIG"
 printf '%d\n' "$TOOSMALL"
 
+printf '%d\n' ''
+printf '%d\n' ' '
+printf '%*.*d\n' 10 '' 30
+printf '%*.*d\n' '' 10 30
+
 # tests variable assignment with -v
 ${THIS_SH} ./printf1.sub
 ${THIS_SH} ./printf2.sub
-- 
2.47.0

Reply via email to