Consider the following shell script 'doit':

sp=' '
nl='
'
test "${sp}1${sp}" -lt "${sp}2${sp}"
test "${nl}3${sp}" -lt "${nl}4${sp}"
test "${sp}5${nl}" -lt "${sp}6${nl}"
test "${nl}7${nl}" -lt "${nl}8${nl}"

Running the command "bash doit" outputs:

doit: line 6: test:  5
: integer expression expected
doit: line 7: test:
7
: integer expression expected

The problem occurs because strtoimax accepts all forms of leading whitespace, whereas Bash accepts only space and tab after the integer. This is inconsistent: Bash should treat trailing whitespace the same way it treats leading whitespace, and should accept all of doit's 'test' commands, as Dash does.

Proposed patch attached.
From bb2403a3ae6a39631777a7deea3d7f8128fff764 Mon Sep 17 00:00:00 2001
From: Paul Eggert <egg...@cs.ucla.edu>
Date: Sat, 28 Oct 2023 12:05:14 -0700
Subject: [PATCH] fix inconsistency when parsing integers

* general.c (legal_number): Treat trailing whitespace
like leading whitespace.
---
 general.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/general.c b/general.c
index da59f9c0..3e63f9f7 100644
--- a/general.c
+++ b/general.c
@@ -256,7 +256,7 @@ legal_number (const char *string, intmax_t *result)
     return 0;	/* errno is set on overflow or underflow */
 
   /* Skip any trailing whitespace, since strtoimax does not. */
-  while (whitespace (*ep))
+  while (isspace ((unsigned char) *ep))
     ep++;
 
   /* If *string is not '\0' but *ep is '\0' on return, the entire string
-- 
2.41.0

Reply via email to