Golang - 执行shell脚本,实时输出shell脚本中的日志

Golang - 执行shell脚本,实时输出shell脚本中的日志: 

package main

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

func SafetyShell(execName string, arg ...string) (string, error) {
	ex := exec.Command(execName, arg...)
	result, err := ex.CombinedOutput()
	if err != nil {
		return "", err
	}

	return strings.TrimSpace(string(result)), nil
}

func execSH() bool {
	execSH := []string{"./exec.sh"}
	res, err := SafetyShell("/bin/sh", execSH...)
	fmt.Println(fmt.Sprintf("res: %+v", res))
	fmt.Println(fmt.Sprintf("err: %+v", err))
	if err != nil {
		return false
	}
	return true
}

func executeShellScript(execName string, arg ...string) error {
	cmd := exec.Command(execName, arg...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return err
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		return err
	}

	if err := cmd.Start(); err != nil {
		return err
	}

	go func() {
		reader := bufio.NewReader(stderr)
		for {
			line, err := reader.ReadString('\n')
			if err != nil || io.EOF == err {
				break
			}
			fmt.Print(line)
		}
	}()

	reader := bufio.NewReader(stdout)
	for {
		line, err := reader.ReadString('\n')
		if err != nil || io.EOF == err {
			break
		}
		fmt.Print(line)
	}

	if err := cmd.Wait(); err != nil {
		return err
	}

	return nil
}

func main() {
	//flag := execSH()
	//fmt.Println("flag : ", flag)

	// 可以实时输出shell脚本中的echo输出,和错误输出
	execSH := []string{"./exec.sh"}
	err := executeShellScript("/bin/sh", execSH...)
	if err != nil {
		fmt.Println("Error:", err)
	}

}

你可能感兴趣的:(Golang,golang,开发语言,后端)