[go-每日一库] golang 通过os/exec执行shell命令
直接上代码:
package main
import (
"fmt"
"os/exec"
"time"
)
func main() {
// 执行并等待结束,正确执行返回nil error, 同步
fmt.Println("cmd with run,", time.Now())
cmd := exec.Command("sleep", "10")
_ = cmd.Run() // start + wait
fmt.Println("exec end, ", <- time.After(10*time.Second))
/*
cmd with run, 2022-06-25 10:34:35.6105608 +0800 CST m=+0.002574201
exec end, 2022-06-25 10:34:45.6328703 +0800 CST m=+10.024849701
*/
// 执行但不等待结束,异步
fmt.Println("cmd with start,", time.Now())
cmd1 := exec.Command("sleep", "10")
_ = cmd1.Start()
fmt.Println("exec start end")
/*
cmd with start, 2022-06-25 10:34:45.6328703 +0800 CST m=+10.024849701
exec start end
*/
}
参考: