I'm running a really simple bash script which just echo's some data within Go. I've placed this into a wrapper and used the exec package to execute this. This works nicely by outputting to my terminal, however, I can't find any way to actually store this into a variable in Go.
I'm new to Go, so my debugging skills aren't amazing. However, I've placed some basic logging outputs to try to narrow down where exactly I need to get the output from, but to no avail.
The two functions which run bash:
func main(){
_, result,_ := runBash()
log.Printf("Result: ", result)
}
func runBash()(bool, string, string){
cmd := exec.Command("/bin/sh", "-s")
cmd.Stdin = strings.NewReader(replicateRouter())
return finishRunning(cmd)
}
func finishRunning(cmd *exec.Cmd) (bool, string, string) {
log.Printf("Running: ")
stdout, stderr := bytes.NewBuffer(nil), bytes.NewBuffer(nil)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
done := make(chan struct{})
defer close(done)
go func() {
for {
select {
case <-done:
return
case s := <-signals:
cmd.Process.Signal(s)
}
}
}()
log.Printf("Flag 1")
if err := cmd.Run(); err != nil {
log.Printf("Error running %v", err)
return false, string(stdout.Bytes()), string(stderr.Bytes())
}
log.Printf("Flag 2")
return true, string(stdout.Bytes()), ""
}
This is the function to fake test my bash script:
func replicateRouter() string{
return `echo <HOSTNAME> <IP> <MACADDRESS>`
}
The echo happens between flag 1 & 2 and at any point when I try to log any values from cmd/stdout I get empty strings. Within the main function, the result variable produces:
2020/06/19 18:17:14 Result: %!(EXTRA string=)
So I suppose my first question is why isn't result (which is in theory string(stdout.Bytes())) not producing the echo? & Secondly, where/how can I save the output to a variable?
Thanks & feel free to ping me if I've missed any questions &/or need more details
--Edit: Also forgot to mention, the code was heavily inspired by this Kubernetes go script. If there are any recommendations/criticism to doing it this way, I'd be really happy to hear/learn :)