0

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?

ain
  • 22,394
  • 3
  • 54
  • 74
Akshay komarla
  • 722
  • 1
  • 11
  • 20
  • Why are you executing all your bash commands in one go? I would probably create a method for executing command and returning the output. By doing this it would be easier to log the command and the result of the command. – Buddy Jan 03 '23 at 13:31
  • You are sending an opaque string to `bash` for execution, there's nothing you can do after that point. Using `-x` for `bash` will echo the commands back in bash's debug format if that is acceptable, otherwise you need to record and execute the commands separately on your own. – JimB Jan 03 '23 at 14:13

0 Answers0