Go でシェルコマンドを実行する
シェルコマンドは、特定のタスクを実行する方法をシステムに指示します。外部コマンドは、パッケージ exec を介して実行されます。
os / exec パッケージは、C や他の言語からのシステムライブラリ呼び出しとは異なり、システムシェルを実行せず、glob パターンを拡張したり、シェルのような拡張、パイプライン、またはリダイレクトを処理したりしません。
このパッケージは、C 言語の exec ファミリーの関数に似ています。
この記事では、Golang でシェルまたは外部コマンドを実行する方法を学習します。
Go で os/exec パッケージを使用してシェルコマンドを実行する
Go の os/exec パッケージを使用して、任意の OS またはシステムコマンドをトリガーできます。これを行うために使用できる 2つの関数を提供します。cmd オブジェクトを作成する Command と、コマンドを実行して標準出力を返す Output です。
package main
import (
    "fmt"
    "log"
    "os/exec"
)
func main() {
    out, err := exec.Command("pwd").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(out))
}
出力:
It will return the location of your current working directory.
それでは、os/exec パッケージを使用して ls のような単純なコマンドを実行する方法を見てみましょう。
まず、fmt、os / exec、runtime の 3つの重要なパッケージをインポートする必要があります。その後、コードの実行を開始する execute() メソッドを作成します。
package main
import (
    "fmt"
    "os/exec"
    "runtime"
)
func execute() {
    out, err := exec.Command("ls").Output()
    if err != nil {
        fmt.Printf("%s", err)
    }
    fmt.Println("Program executed")
    output := string(out[:])
    fmt.Println(output)
}
func main() {
    if runtime.GOOS == "windows" {
        fmt.Println("This program is not aplicable for windows machine.")
    } else {
        execute()
    }
}
出力:
Program executed
bin
dev
etc
home
lib
lib64
proc
root
sys
tmp
tmpfs
usr
var
Go で引数を渡して os/exec パッケージを使用してシェルコマンドを実行する
Command 関数は、指定されたパラメーターを使用して提供されたプログラムを実行できる Cmd 構造体を返します。最初の引数は実行されるプログラムです。他の引数はプログラムパラメータです。
package main
import (
    "bytes"
    "fmt"
    "log"
    "os/exec"
    "strings"
)
func main() {
    cmd := exec.Command("tr", "a-z", "A-Z")
    cmd.Stdin = strings.NewReader("Hello Boss!")
    var out bytes.Buffer
    cmd.Stdout = &out
    err := cmd.Run()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("New Message: %q\n", out.String())
}
出力:
New Message: "HELLO BOSS!"
        チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe