github.com/metacubex/mihomo@v1.18.5/common/cmd/cmd.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os/exec"
     6  	"strings"
     7  )
     8  
     9  func ExecCmd(cmdStr string) (string, error) {
    10  	args := splitArgs(cmdStr)
    11  
    12  	var cmd *exec.Cmd
    13  	if len(args) == 1 {
    14  		cmd = exec.Command(args[0])
    15  	} else {
    16  		cmd = exec.Command(args[0], args[1:]...)
    17  
    18  	}
    19  	prepareBackgroundCommand(cmd)
    20  	out, err := cmd.CombinedOutput()
    21  	if err != nil {
    22  		return "", fmt.Errorf("%v, %s", err, string(out))
    23  	}
    24  	return string(out), nil
    25  }
    26  
    27  func splitArgs(cmd string) []string {
    28  	args := strings.Split(cmd, " ")
    29  
    30  	// use in pipeline
    31  	if len(args) > 2 && strings.ContainsAny(cmd, "|") {
    32  		suffix := strings.Join(args[2:], " ")
    33  		args = append(args[:2], suffix)
    34  	}
    35  	return args
    36  }