I have the following program executing shell commands using exec.Command()
in os/exec
golang package and capturing the output.
package main
import (
"bufio"
"fmt"
"os/exec"
)
func main() {
cmd := exec.Command("bash", "-c", "ls -la; go version; date;")
stdout, _ := cmd.StdoutPipe()
logChan := make(chan string)
_ = cmd.Start()
scanner := bufio.NewScanner(stdout)
scanner.Split(bufio.ScanLines)
go sendLog(logChan, scanner)
for l := range logChan {
fmt.Println(l)
}
cmd.Wait()
}
func sendLog(logChan chan<- string, scanner *bufio.Scanner) {
defer close(logChan)
for scanner.Scan() {
m := scanner.Text()
logChan <- m
}
}
Output:
total 8
drwxr-xr-x 3 akshayd staff 96 3 Jan 15:20 .
drwxr-xr-x 11 akshayd staff 352 3 Jan 15:20 ..
-rw-r--r-- 1 akshayd staff 542 3 Jan 16:29 main.go
go version go1.18.1 darwin/arm64
Tue 3 Jan 2023 16:29:14 IST
Along with the output i also want to capture the command its executing. Like this.
ls -la
total 8
drwxr-xr-x 3 akshayd staff 96 3 Jan 15:20 .
drwxr-xr-x 11 akshayd staff 352 3 Jan 15:20 ..
-rw-r--r-- 1 akshayd staff 542 3 Jan 16:29 main.go
go version
go version go1.18.1 darwin/arm64
date
Tue 3 Jan 2023 16:29:14 IST
How can i acheive this?