我试图在go中执行bash命令"hello world" | /usr/bin/pbcopy:
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我希望剪贴板等同于“你好世界”,但事实并非如此。
更新
我试过用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)
}..。但是剪贴板仍然不能等同于“你好世界”。
发布于 2015-05-08 00:35:26
Command接受一个可执行文件和一个参数列表。所以当你打电话
exec.Command(`echo "hello world"`)这实际上是试图运行一个名为echo "hello world"的命令(带有空格和引号)。正如您已经了解到的,exec.Command不会将东西传递给shell,因此“AC.26”也不会以这种方式工作。所以如果你要把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()
}https://stackoverflow.com/questions/30095870
复制相似问题