Pipe a command and redirect the output with command

依然范特西╮ 提交于 2021-02-08 08:37:16

问题


Here is my code:

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())
    }


}

I would like to do it in one command.

My second line the zfs send command seems not working.

How to pipe and redirect the ouput in golang with cmd.exec?


回答1:


This is a simplified version of how you would achieve this:

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()

It is equivalent to this command in the shell:

zfs send stored@backup | gzip -cf > backup.gz


来源:https://stackoverflow.com/questions/53350657/pipe-a-command-and-redirect-the-output-with-command

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!