os.exec.Command and pbcopy



我正在尝试执行bash命令 "hello world" | /usr/bin/pbcopy go:

package main
import (
    "fmt"
    "os/exec"
    "strings"
)
func Cmd(cmd string) {
    fmt.Println("command is ", cmd)
    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.Println("out")
    fmt.Println(string(out))
}
func main() {
    Cmd(`echo "hello world" | /usr/bin/pbcopy`)
}

当我运行此go文件时,它会输出:

command is  echo "hello world" | /usr/bin/pbcopy
out
"hello world" | /usr/bin/pbcopy

我希望剪贴板等于" Hello World"。但不是。

更新

我尝试使用io.Pipe

package main
import (
    "bytes"
    "io"
    "os"
    "os/exec"
)
func main() {
    c1 := exec.Command(`echo "hello world"`)
    c2 := exec.Command("/usr/bin/pbcopy")
    r, w := io.Pipe()
    c1.Stdout = w
    c2.Stdin = r
    var b2 bytes.Buffer
    c2.Stdout = &b2
    c1.Start()
    c2.Start()
    c1.Wait()
    w.Close()
    c2.Wait()
    io.Copy(os.Stdout, &b2)
}

...但是剪贴板仍然不等于" Hello World"

Command获取可执行文件和参数列表。因此,当您致电

exec.Command(`echo "hello world"`)

实际上试图运行一个名为echo "hello world"的命令(带有空间和引号)。正如您已经学到的那样,exec.Command不会将事物传递给外壳,所以" |"这两种方式都无法工作。因此,如果您要通过将Stdout和Stdin绑在一起将所有内容拼凑在一起,则看起来像这样:

func main() {
    c1 := exec.Command("echo", "hello world")
    c2 := exec.Command("/usr/bin/pbcopy")
    c1stdout, _ := c1.StdoutPipe()
    c2stdin, _ := c2.StdinPipe()
    c1.Start()
    c2.Start()
    io.Copy(c2stdin, c1stdout)
    c2stdin.Close()
    c2.Wait()
}

,但无需所有这些。你有一个外壳。如果您要求它,它可以为您完成所有这些。

func main() {
    exec.Command("sh", "-c", `echo "hello world" | pbcopy`).Run()
}

最新更新