Skip to content

Commit

Permalink
expand: fix parameters with leading/trailing spaces
Browse files Browse the repository at this point in the history
That is:

	$ a=" b c "
	$ echo foo${a}bar
	foo b c bar

rather than our previous incorrect answer:

	$ a=" b c "
	$ echo foo${a}bar
	foob cbar

Our error was relying on strings.FieldsFunc, which performs exactly as
documented, but is not enough for us - we need to know whether the
expanded string has leading or trailing IFS characters.

Fixes #886.
  • Loading branch information
mvdan committed Jun 28, 2022
1 parent 5146d3e commit fc3e0c7
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
17 changes: 14 additions & 3 deletions expand/expand.go
Original file line number Diff line number Diff line change
Expand Up @@ -546,11 +546,22 @@ func (cfg *Config) wordFields(wps []syntax.WordPart) ([][]fieldPart, error) {
curField = nil
}
splitAdd := func(val string) {
for i, field := range strings.FieldsFunc(val, cfg.ifsRune) {
if i > 0 {
fieldStart := -1
for i, r := range val {
if cfg.ifsRune(r) {
if fieldStart >= 0 { // ending a field
curField = append(curField, fieldPart{val: val[fieldStart:i]})
fieldStart = -1
}
flush()
} else {
if fieldStart < 0 { // starting a new field
fieldStart = i
}
}
curField = append(curField, fieldPart{val: field})
}
if fieldStart >= 0 { // ending a field without IFS
curField = append(curField, fieldPart{val: val[fieldStart:]})
}
}
for i, wp := range wps {
Expand Down
2 changes: 2 additions & 0 deletions interp/interp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,8 @@ var runTests = []runTest{
{`echo a'b'c"d"e`, "abcde\n"},
{`a=" b c "; echo $a`, "b c\n"},
{`a=" b c "; echo "$a"`, " b c \n"},
{`a=" b c "; echo foo${a}bar`, "foo b c bar\n"},
{`a="b c"; echo foo${a}bar`, "foob cbar\n"},
{`echo "$(echo ' b c ')"`, " b c \n"},
{"echo ''", "\n"},
{`$(echo)`, ""},
Expand Down

0 comments on commit fc3e0c7

Please sign in to comment.