on Linux/macOS, launch external commands directly without using the shell

This commit is contained in:
aler9 2022-01-25 14:55:50 +01:00
parent d3bf643f77
commit 3a81728096
3 changed files with 16 additions and 12 deletions

View File

@ -1,6 +1,7 @@
package externalcmd package externalcmd
import ( import (
"strings"
"time" "time"
) )
@ -31,6 +32,10 @@ func NewCmd(
env Environment, env Environment,
onExit func(int), onExit func(int),
) *Cmd { ) *Cmd {
for key, val := range env {
cmdstr = strings.ReplaceAll(cmdstr, "$"+key, val)
}
e := &Cmd{ e := &Cmd{
pool: pool, pool: pool,
cmdstr: cmdstr, cmdstr: cmdstr,

View File

@ -7,10 +7,17 @@ import (
"os" "os"
"os/exec" "os/exec"
"syscall" "syscall"
"github.com/kballard/go-shellquote"
) )
func (e *Cmd) runInner() (int, bool) { func (e *Cmd) runInner() (int, bool) {
cmd := exec.Command("/bin/sh", "-c", "exec "+e.cmdstr) cmdparts, err := shellquote.Split(e.cmdstr)
if err != nil {
return 0, true
}
cmd := exec.Command(cmdparts[0], cmdparts[1:]...)
cmd.Env = append([]string(nil), os.Environ()...) cmd.Env = append([]string(nil), os.Environ()...)
for key, val := range e.env { for key, val := range e.env {
@ -20,7 +27,7 @@ func (e *Cmd) runInner() (int, bool) {
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
err := cmd.Start() err = cmd.Start()
if err != nil { if err != nil {
return 0, true return 0, true
} }

View File

@ -6,25 +6,17 @@ package externalcmd
import ( import (
"os" "os"
"os/exec" "os/exec"
"strings"
"github.com/kballard/go-shellquote" "github.com/kballard/go-shellquote"
) )
func (e *Cmd) runInner() (int, bool) { func (e *Cmd) runInner() (int, bool) {
// On Windows, the shell is not used and command is started directly. cmdparts, err := shellquote.Split(e.cmdstr)
// Variables are replaced manually in order to guarantee compatibility
// with Linux commands.
tmp := e.cmdstr
for key, val := range e.env {
tmp = strings.ReplaceAll(tmp, "$"+key, val)
}
parts, err := shellquote.Split(tmp)
if err != nil { if err != nil {
return 0, true return 0, true
} }
cmd := exec.Command(parts[0], parts[1:]...) cmd := exec.Command(cmdparts[0], cmdparts[1:]...)
cmd.Env = append([]string(nil), os.Environ()...) cmd.Env = append([]string(nil), os.Environ()...)
for key, val := range e.env { for key, val := range e.env {