【golang】golang执行shell脚本返回错误码


sout, err := linux.ExecCmd(action)
if err != nil {
	errcode := 0
	exitError, ok := err.(*exec.ExitError)
	if ok {
		errcode = exitError.ExitCode()
	}
	out := _TrimTail(sout)
	g.Log().Warningf(ctx, "ExecCmd fail, {%v}, \n\tCmd: \n%v, \n\tOut-RetCode: %v\n\tOut: \n%v", err, action, errcode, out)
	return
}


func ExecCmd_Advance(strCmd string) (status int, out string, err error) {
	cmd := exec.Command("/bin/bash", "-c", strCmd)
	stdout, err := cmd.StdoutPipe()
	if err != nil {
		return
	}
	cmd.Start()
	if err != nil {
		return
	}

	//创建一个流来读取管道内内容,这里逻辑是通过一行一行的读取的
	reader := bufio.NewReader(stdout)
	//实时循环读取输出流中的一行内容
	for {
		line, err2 := reader.ReadString('\n')
		if err2 != nil || io.EOF == err2 {
			break
		}
		out += line
	}

	if err := cmd.Wait(); err != nil {
		exitError, ok := err.(*exec.ExitError)
		if ok {
			status = exitError.ExitCode()
		}
	}
	return
}
posted @ 2022-05-26 16:56  jiftle  阅读(530)  评论(0编辑  收藏  举报