Skip to content

Commit

Permalink
fix trying to parse subshell calls as env vars
Browse files Browse the repository at this point in the history
Parser didn't detect subshell calls, $(), and tried to parse them as
environment variables. This picks up the $( pattern and continues on
with parsing, leaving it as is.

Added tests for it as well.
  • Loading branch information
eikenb committed Jun 15, 2021
1 parent 973b9d5 commit c90ad31
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 1 deletion.
7 changes: 6 additions & 1 deletion shellwords.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,12 @@ func replaceEnv(getenv func(string) string, s string) string {
buf.WriteRune(r)
break
}
if rs[i] == 0x7b {
if rs[i] == '(' { // subshell call, not env variable
buf.WriteRune(rs[i-1])
buf.WriteRune(rs[i])
continue
}
if rs[i] == 0x7b { // '{', bracketed shell variable
i++
p := i
for ; i < len(rs); i++ {
Expand Down
40 changes: 40 additions & 0 deletions shellwords_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -503,4 +503,44 @@ func TestSubShellEnv(t *testing.T) {
t.Fatalf(errTmpl, expected, args)
}
})

t.Run("single-quoted-subshell-call", func(t *testing.T) {
args, err := myParser.Parse(`sh -c 'echo $(foo)'`)
if err != nil {
t.Fatalf("err should be nil: %v", err)
}
expected := []string{"sh", "-c", "echo $(foo)"}
if len(args) != 3 {
t.Fatalf(errTmpl, expected, args)
}
if args[0] != expected[0] || args[1] != expected[1] || args[2] != expected[2] {
t.Fatalf(errTmpl, expected, args)
}
})
t.Run("double-quoted-subshell-call", func(t *testing.T) {
args, err := myParser.Parse(`sh -c "echo $(foo)"`)
if err != nil {
t.Fatalf("err should be nil: %v", err)
}
expected := []string{"sh", "-c", "echo $(foo)"}
if len(args) != 3 {
t.Fatalf(errTmpl, expected, args)
}
if args[0] != expected[0] || args[1] != expected[1] || args[2] != expected[2] {
t.Fatalf(errTmpl, expected, args)
}
})
t.Run("subshell-call-call", func(t *testing.T) {
args, err := myParser.Parse(`sh -c "echo $(foo $(bar))"`)
if err != nil {
t.Fatalf("err should be nil: %v", err)
}
expected := []string{"sh", "-c", "echo $(foo $(bar))"}
if len(args) != 3 {
t.Fatalf(errTmpl, expected, args)
}
if args[0] != expected[0] || args[1] != expected[1] || args[2] != expected[2] {
t.Fatalf(errTmpl, expected, args)
}
})
}

0 comments on commit c90ad31

Please sign in to comment.