bitfield / script

Making it easy to write shell-like scripts in Go
MIT License
5.55k stars 315 forks source link

Added Tee and SetStderr #166

Closed rmasci closed 1 year ago

rmasci commented 1 year ago

Tee allows you to write to an io.Writer and to print to stdout as per issue 145. I have included code to script.go, as well as script_testing.go, and an example in the readme file. Use:

tn:=time.Now().Format("2006-01-02-15.04")
fileName:=fmt.Sprintf("appSales-%s",tn)
outFile, err := os.Openfile("/path/to/file/"+fileName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
script.Get("https://myserver.somewhere.org/application/json/status.json"`).Tee(outFile).JQ(".orders[].purchased.price").Tee(outFile).Stdout()
if err != nil {
    panic(err)
}

SetStderr is a case I opened issue 128. I have also added some code to script.go, and script_testing.go. This allows you to set an io.writer to stderr so that both are not in the output. This solved the issue I had where my company uses in the /etc/ssh/sshd_config a directive: 'Banner /etc/corp_motd'. So if I wanted a report on the uptime of 20 servers, I just get the stdout and not the corp_motd mixed in.
Use:

pipe := script.NewPipe()
pipe.SetStderr(io.Discard)
for _, host := range myhosts {
    cmd := fmt.Sprintf("ssh %s uptime", host)
    str, err := pipe.Exec(cmd).String()
    if err != nil {
        log.Printf("error %v %v\n", err, pipe.Error())
    } else {
        fmt.Println(strings.TrimSpace(str))
    }
}  
bitfield commented 1 year ago

Fixed in bee12905b647e8b1eb615b407d6bbd0c7d7e9df7 and 7acd35c9f49cff6f7f16c5b5522753dbb19ef0ac, thanks @rmasci!