如何在Golang中以未知参数执行系统命令

我有一堆系统命令,它们类似于将新内容附加到文件。我写了一个简单的脚本来执行系统命令,如果有单词如’ls’,’date’等等,那么这个命令的效果很好。但是如果命令大于这个程序,程序就会死机。

以下是代码

package main

import (
    "fmt"
    "os/exec"
    "sync"
)

func exe_cmd(cmd string,wg *sync.WaitGroup) {
    fmt.Println(cmd)
    c = cmd.Str
    out,err := exec.Command(cmd).Output()
    if err != nil {
        fmt.Println("error occured")
        fmt.Printf("%s",err)
    }
    fmt.Printf("%s",out)
    wg.Done()
}

func main() {
    wg := new(sync.WaitGroup)
    wg.Add(3)

    x := []string{"echo newline >> foo.o","echo newline >> f1.o","echo newline >> f2.o"}
    go exe_cmd(x[0],wg)
    go exe_cmd(x[1],wg)
    go exe_cmd(x[2],wg)

    wg.Wait()
}

以下是我看到的错误

exec: "echo newline >> foo.o": executable file not found in $PATHexec: 
"echo newline >> f2.o": executable file not found in $PATHexec: 
"echo newline >> f1.o": executable file not found in $PATH

我猜,这可能是因为,不单独发送cmds和论据(http://golang.org/pkg/os/exec/#Command)。我想知道如何颠覆这个,因为我不知道我的命令中将有多少个参数需要执行。

我发现一个比较体面的方式来实现这一点。
out,err := exec.Command("sh","-c",cmd).Output()

为我工作,直到现在。仍然找到更好的方式来实现这一点。

EDIT1:

最后一个更简单和高效(至少到目前为止)的做法就是这样

func exe_cmd(cmd string,wg *sync.WaitGroup) {
  fmt.Println("command is ",cmd)
  // splitting head => g++ parts => rest of the command
  parts := strings.Fields(cmd)
  head := parts[0]
  parts = parts[1:len(parts)]

  out,err := exec.Command(head,parts...).Output()
  if err != nil {
    fmt.Printf("%s",err)
  }
  fmt.Printf("%s",out)
  wg.Done() // Need to signal to waitgroup that this goroutine is done
}

感谢你们中的各种各样的论据,并指出我的人:)

相关文章

什么是Go的接口? 接口可以说是一种类型,可以粗略的理解为他...
1、Golang指针 在介绍Golang指针隐式间接引用前,先简单说下...
1、概述 1.1 Protocol buffers定义 Protocol buffe...
判断文件是否存在,需要用到"os"包中的两个函数: os.Stat(...
1、编译环境 OS :Loongnix-Server Linux release 8.3 CPU指...
1、概述 Golang是一种强类型语言,虽然在代码中经常看到i:=1...