GO语言运行cmd命令逐行实时输出执行过程

package main

import (
    "bufio"
    "fmt"
    "io"
    "os/exec"
    "strings"
    "os"
)
/*

# test.sh
#!/bin/bash

for k in $( seq 1 10 )
do
   echo "Hello World $k"
   sleep 1
done

 */

var contentArray = make([]string, 0, 5)

func main() {
    command := "/bin/bash"
    params := []string{"-c", "sh /Users/zhangbaozhen/codespace/hhmedic/script/test.sh"}

    execCommand(command, params)
}

func execCommand(commandName string, params []string) bool {
    contentArray = contentArray[0:0]
    cmd := exec.Command(commandName, params...)
    //显示运行的命令
    fmt.Printf("执行命令: %s\n", strings.Join(cmd.Args[1:], " "))
    stdout, err := cmd.StdoutPipe()
    if err != nil {
        fmt.Fprintln(os.Stderr, "error=>", err.Error())
        return false
    }
    cmd.Start() // Start开始执行c包含的命令,但并不会等待该命令完成即返回。Wait方法会返回命令的返回状态码并在命令返回后释放相关的资源。

    reader := bufio.NewReader(stdout)

    var index int
    //实时循环读取输出流中的一行内容
    for {
        line, err2 := reader.ReadString('\n')
        if err2 != nil || io.EOF == err2 {
            break
        }
        fmt.Println(line)
        index++
        contentArray = append(contentArray, line)
    }

    cmd.Wait()
    return true
}


你可能感兴趣的:(golang)