Skip to content

Commit 279b806

Browse files
committed
expand,interp: trim whitespace in atoi
Fixes #928.
1 parent 6ba49e2 commit 279b806

File tree

3 files changed

+20
-4
lines changed

3 files changed

+20
-4
lines changed

expand/arith.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ package expand
66
import (
77
"fmt"
88
"strconv"
9+
"strings"
910

1011
"mvdan.cc/sh/v3/syntax"
1112
)
@@ -105,9 +106,9 @@ func oneIf(b bool) int {
105106
return 0
106107
}
107108

108-
// atoi is just a shorthand for strconv.Atoi that ignores the error,
109-
// just like shells do.
109+
// atoi is like strconv.Atoi, but it ignores errors and trims whitespace.
110110
func atoi(s string) int {
111+
s = strings.TrimSpace(s)
111112
n, _ := strconv.Atoi(s)
112113
return n
113114
}

interp/builtin.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -32,16 +32,18 @@ func isBuiltin(name string) bool {
3232
return false
3333
}
3434

35+
// TODO: oneIf and atoi are duplicated in the expand package.
36+
3537
func oneIf(b bool) int {
3638
if b {
3739
return 1
3840
}
3941
return 0
4042
}
4143

42-
// atoi is just a shorthand for strconv.Atoi that ignores the error,
43-
// just like shells do.
44+
// atoi is like strconv.Atoi, but it ignores errors and trims whitespace.
4445
func atoi(s string) int {
46+
s = strings.TrimSpace(s)
4547
n, _ := strconv.Atoi(s)
4648
return n
4749
}

interp/interp_test.go

+13
Original file line numberDiff line numberDiff line change
@@ -1412,6 +1412,10 @@ var runTests = []runTest{
14121412
"[[ 3 -lt 4 ]]",
14131413
"",
14141414
},
1415+
{
1416+
"[[ ' 3' -lt '4 ' ]]",
1417+
"",
1418+
},
14151419
{
14161420
"[[ 3 -gt 4 ]]",
14171421
"exit status 1",
@@ -1637,6 +1641,7 @@ var runTests = []runTest{
16371641
{"[ 0 -gt 1 -o 1 -gt 0 ]", ""},
16381642
{"[ 3 -gt 4 ]", "exit status 1"},
16391643
{"[ 3 -lt 4 ]", ""},
1644+
{"[ ' 3' -lt '4 ' ]", ""},
16401645
{
16411646
"[ -e a ] && echo x; >a; [ -e a ] && echo y",
16421647
"y\n",
@@ -1826,6 +1831,14 @@ var runTests = []runTest{
18261831
"let x=3; let 3%0; ((3%0)); echo $((x%y)); let x%=0",
18271832
"division by zero\ndivision by zero\ndivision by zero\ndivision by zero\nexit status 1 #JUSTERR",
18281833
},
1834+
{
1835+
"let x=' 3'; echo $x",
1836+
"3\n",
1837+
},
1838+
{
1839+
"x=' 3'; let x++; echo \"$x\"",
1840+
"4\n",
1841+
},
18291842

18301843
// set/shift
18311844
{

0 commit comments

Comments
 (0)