2
0

More than 3 years have passed since last update.

Golang シェル実行

Last updated at Posted at 2020-05-03
package main

import (
    "fmt"
    "os"
    "os/exec"
    "strings"
)

func getstatusoutput(args ...string) (status int, output string) {
    exec_command := exec.Command(args[0], args[1:]...)
    std_out, std_err := exec_command.Output()
    status = exec_command.ProcessState.ExitCode()
    if std_err != nil {
        output = std_err.Error()
    } else {
        output = string(std_out)
    }
    return
}

func main() {
    // command := []string{"echo", "-n", "HelloWorld"}
    command_line := "echo  -n   HelloWorld"
    command := strings.Fields(command_line)
    shell := os.Getenv("SHELL")
    status, output := getstatusoutput(command...)
    fmt.Printf("--- Result ---------------\n")
    fmt.Printf("Shell        : %s\n", shell)
    fmt.Printf("Command      : %s\n", command)
    fmt.Printf("StatusCode   : %d\n", status)
    fmt.Printf("ResultMessage: %s\n", output)
    fmt.Printf("--------------------------\n")

}

結果

--- Result ---------------
Shell        : /bin/bash
Command      : [echo -n HelloWorld]
StatusCode   : 0
ResultMessage: HelloWorld
--------------------------

意図的に失敗させる
(typo echo -> echa)

--- Result ---------------
Shell        : /bin/bash
Command      : [echa -n HelloWorld]
StatusCode   : -1
ResultMessage: exec: "echa": executable file not found in $PATH
--------------------------

参考

Package exec
https://golang.org/pkg/os/exec/

Goでコマンドを実行して終了コードを取得する方法
https://qiita.com/hnakamur/items/5e6f22bda8334e190f63

In Golang, how to convert an error to a string?
https://www.systutorials.com/in-golang-how-to-convert-an-error-to-a-string/

2
0
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
2
0