Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Go で外部コマンド実行
package main
import (
"fmt"
"os/exec"
"time"
"strings"
)
func main() {
fmt.Println("======= 01 Run")
err := exec.Command("date").Run()
if err != nil {
fmt.Println(err)
}
fmt.Println("======= 02 Output")
out,err := exec.Command("date").Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
fmt.Println("======= 03 Start")
fmt.Println("Start : ",time.Now().Format("15:04:05"))
cmd := exec.Command("sleep", "5s")
cmd.Start()
fmt.Println("sleep : ",time.Now().Format("15:04:05"))
cmd.Wait()
fmt.Println("End : ",time.Now().Format("15:04:05"))
fmt.Println("======= 04 args")
cmd_str := "ls -l -a"
cmd_arry := strings.Split(cmd_str, " ")
out, err = exec.Command(cmd_arry[0], cmd_arry[1:]...).Output()
if err != nil {
fmt.Println(err)
}
fmt.Println(string(out))
}
======= 01 Run
======= 02 Output
2018年 11月 6日 火曜日 18:21:51 JST
======= 03 Start
Start : 18:21:51
sleep : 18:21:51
End : 18:21:56
======= 04 args
合計 12
drwxrwxr-x 2 hoge hoge 4096 11月 6 18:21 2018 .
drwxrwxr-x 4 hoge hoge 4096 11月 6 18:05 2018 ..
-rw-rw-r-- 1 hoge hoge 0 11月 6 18:06 2018 aaaa
-rw-rw-r-- 1 hoge hoge 0 11月 6 18:06 2018 ddddd
-rw-rw-r-- 1 hoge hoge 974 11月 6 18:21 2018 do_command.go
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.