1Panel/backend/utils/cmd/cmd.go

32 lines
615 B
Go
Raw Normal View History

package cmd
import (
2022-11-08 15:42:31 +08:00
"bytes"
"fmt"
"os/exec"
)
2022-11-08 15:42:31 +08:00
func Exec(cmdStr string) (string, error) {
cmd := exec.Command("bash", "-c", cmdStr)
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
2022-11-18 18:02:14 +08:00
return stderr.String(), err
}
2022-11-18 18:02:14 +08:00
return stdout.String(), nil
}
func Execf(cmdStr string, a ...interface{}) (string, error) {
cmd := exec.Command("bash", "-c", fmt.Sprintf(cmdStr, a...))
var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr
err := cmd.Run()
if err != nil {
return stderr.String(), err
}
return stdout.String(), nil
}