github.com/yaling888/clash@v1.53.0/common/cmd/cmd.go (about)

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