需求,go语言程序执行个shell并取得结果赋值输出,代码示例:
package main
import (
"log"
"os/exec"
"bytes"
)
var vms_host string
func main() {
log.SetFlags(0)
cmd := exec.Command("/bin/bash", "-c", "ip addr |grep inet |grep -v inet6|sed -n '2p'")
var out bytes.Buffer
cmd.Stdout = &out
cmd.Run()
vms_host = out.String()
log.Print("vms_host:"+vms_host)
}
执行结果记得替换下换行符哦.
未经允许不得转载:阿藏博客 » go语言执行shell并获取结果赋值