Skip to content

Instantly share code, notes, and snippets.

@didip
Forked from hivefans/shell_output.go
Last active July 21, 2020 05:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save didip/209783511270356671a4e5147bcf11f7 to your computer and use it in GitHub Desktop.
Save didip/209783511270356671a4e5147bcf11f7 to your computer and use it in GitHub Desktop.
get the realtime output for a shell command in golang|-|{"files":{"shell_output.go":{"env":"plain"}},"tag":"bigdata"}
package main
import (
"bufio"
"fmt"
"io"
"os"
"os/exec"
"strings"
)
func main() {
cmdName := "ping 127.0.0.1"
cmdArgs := strings.Fields(cmdName)
cmd := exec.Command(cmdArgs[0], cmdArgs[1:len(cmdArgs)]...)
stdout, _ := cmd.StdoutPipe()
cmd.Start()
oneByte := make([]byte, 100)
num := 1
for {
_, err := stdout.Read(oneByte)
if err != nil {
fmt.Printf(err.Error())
break
}
r := bufio.NewReader(stdout)
line, _, _ := r.ReadLine()
fmt.Println(string(line))
num = num + 1
if num > 3 {
os.Exit(0)
}
}
cmd.Wait()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment