这是我的代码:
package main
import (
"fmt"
"os"
"os/exec"
"strconv"
"time"
)
func main() {
year, month, day := time.Now().Date()
monthI := int(month)
fmt.Println("toto")
date := strconv.Itoa(year)+"_"+strconv.Itoa(monthI)+"_"+strconv.Itoa(day)
nameSnapshot := "storedb@backup_"+date
args := []string{"snapshot",nameSnapshot}
cmd := exec.Command("zfs", args...)
err := cmd.Run()
if err != nil {
os.Stderr.WriteString(err.Error())
}
args = []string{"send",nameSnapshot,"|","gzip",">","backup_"+date+".gz"}
cmd = exec.Command("zfs", args...)
err = cmd.Run()
if err != nil {
os.Stderr.WriteString(err.Error())
}
}
我想用一个命令来做。
zfs send命令的第二行似乎不起作用。
如何使用cmd.exec对golang中的输出进行管道传输和重定向?
致谢
答案 0 :(得分:1)
这是实现此目的的简化版本:
outfile, _ := os.OpenFile("backup.gz", os.O_RDWR|os.O_CREATE, 0755)
// your zfs command
zfs := exec.Command("zfs", "send", "storedb@backup")
gzip := exec.Command("gzip", "-cf") // gzip to stdout (-cf)
gzip.Stdin, _ = zfs.StdoutPipe() // zfs stdout to gzip stdin
gzip.Stdout = outfile // write output of gzip to outfile
gzip.Start() // gzip start waiting for input
zfs.Run() // zfs start command
gzip.Wait() // gzip wait for pipe to close
outfile.Close()
等效于shell中的此命令:
zfs send stored@backup | gzip -cf > backup.gz