LoginSignup
0
1

More than 3 years have passed since last update.

golangでbashを呼び出す

Posted at

コマンド結果を受け取らず、実行完了まで待機

  • Run

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    err := exec.Command("pwd").Run()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }
}

コマンド結果を受け取る

  • Output

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    out, err := exec.Command("pwd").Output()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }

    // 実行したコマンドの結果を出力
    fmt.Printf("pwd result: %s", string(out))
}

標準出力エラーを受け取る

- CombinedOutput

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    out, err := exec.Command("ls", "dummy").CombinedOutput()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }

    // 実行したコマンドの標準出力+標準エラー出力の内容
    fmt.Printf("ls result: \n%s", string(out))
}

コマンド実行終了を待たない

  • start
  • waitとの組み合わせで待つことができる

package main

import (
    "fmt"
    "os/exec"
)

func main() {
    cmd := exec.Command("sleep", "10")

    fmt.Println("Command Start.")

    err := cmd.Start()
    if err != nil {
        fmt.Println("Command Exec Error.")
    }

    //コメント外すと待機する
    //cmd.Wait()

    fmt.Println("Command Exit.")
}

参考

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1