我正在尝试"hello world" | /usr/bin/pbcopy在 go 中执行 bash 命令:
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)
}
...但剪贴板仍然不等于“你好世界”
相关分类