This is a creation in Article, where the information may have evolved or changed.
How to execute a script and get the return value in Golang
Invoke script
There are two ways to start a process call script in the Golang standard library
The first is the process type in the OS library, and the process type contains a series of methods to start the process and manipulate the process (see: https://golang.org/pkg/os/#Process)
The second is to implement a call to the script in the Os/exec library with various functions of the CMD type, in fact, the CMD is a high-level encapsulation of the various methods in the process (reference: https://golang.org/pkg/os/exec/)
Example using Process Execution script
package mainimport ("fmt""os")func main() {shellPath := "/home/xx/test.sh"argv := make([]string, 1) attr := new(os.ProcAttr)newProcess, err := os.StartProcess(shellPath, argv, attr) //运行脚本if err != nil {fmt.Println(err)}fmt.Println("Process PID", newProcess.Pid)processState, err := newProcess.Wait() //等待命令执行完if err != nil {fmt.Println(err)}fmt.Println("processState PID:", processState.Pid())//获取PIDfmt.Println("ProcessExit:", processState.Exited())//获取进程是否退出}
Execute script with cmd
package mainimport ("fmt""os/exec")func main() {shellPath := "/home/xx/test.sh"command := exec.Command(shellPath) //初始化Cmderr := command.Start()//运行脚本if nil != err {fmt.Println(err)}fmt.Println("Process PID:", command.Process.Pid)err = command.Wait() //等待执行完成if nil != err {fmt.Println(err)}fmt.Println("ProcessState PID:", command.ProcessState.Pid())}
Get Command return value
When the script or command finishes executing, the result is returned to the status in Processstate, but the status is not export, so we need some means to return the script value from Syscall. Waitstatus, find out.
ProcessState定义type ProcessState struct {pid int // The process's id.status syscall.WaitStatus // System-dependent status info.rusage *syscall.Rusage}
For the example above using CMD, you can get the return value from the following statement after the process exits
fmt.Println("Exit Code", command.ProcessState.Sys().(syscall.WaitStatus).ExitStatus())
The process mode can also be obtained by processstate the same way to the returned result.
Look closely at the document, everything is contained inside