Skip to content

Commit

Permalink
expand: don't panic on bad array indexing
Browse files Browse the repository at this point in the history
If an index goes past the end, an empty result is returned.

If an index is negative, we should error.

Both of these cases used to panic.
  • Loading branch information
mvdan committed Dec 2, 2020
1 parent d618d6b commit cf2f340
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 1 deletion.
5 changes: 4 additions & 1 deletion expand/param.go
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,10 @@ func (cfg *Config) varInd(vr Variable, idx syntax.ArithmExpr) (string, error) {
if err != nil {
return "", err
}
if len(vr.List) > 0 {
if i < 0 {
return "", fmt.Errorf("negative array index")
}
if i < len(vr.List) {
return vr.List[i], nil
}
case Associative:
Expand Down
8 changes: 8 additions & 0 deletions interp/interp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2003,6 +2003,14 @@ set +o pipefail
`a=b; echo "${a[@]}"`,
"b\n",
},
{
`a=(b); echo ${a[3]}`,
"\n",
},
{
`a=(b); echo ${a[-2]}`,
"negative array index\nexit status 1 #JUSTERR",
},

// associative arrays
{
Expand Down

0 comments on commit cf2f340

Please sign in to comment.