Call bash with golang

Wait until execution is completed without receiving command result


package main

import (
    "fmt"
    "os/exec"
)

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

Receive command results


package main

import (
	"fmt"
	"os/exec"
)

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

	//Output the result of the executed command
	fmt.Printf("pwd result: %s", string(out))
}

Receive standard output error

- CombinedOutput

package main

import (
	"fmt"
	"os/exec"
)

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

	//Contents of standard output + standard error output of the executed command
	fmt.Printf("ls result: \n%s", string(out))
}

Do not wait for command execution to finish


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.")
	}

	//Wait when uncommented
	//cmd.Wait()

	fmt.Println("Command Exit.")
}

reference

https://blog.y-yuki.net/entry/2017/04/28/000000

Recommended Posts

Call bash with golang
Getting Started with Golang 2
Getting Started with Golang 3
Getting Started with Golang 4
Call the API with python3.
Use MLflow with Databricks ④ --Call model -
Error-free calculation with big.Float of golang
Call C from Python with DragonFFI
Judgment of holidays including holidays with bash
Output the call graph with PyCallGraph
Realize DB connection pool with golang
Generate a Pre-Signed URL with golang
Call python from nim with Nimpy
Realize PHP / Python generator with Golang / Ruby
Convert array (struct) to json with golang
[Golang] Create docker image with Github Actions
Call APIGateWay with APIKey in python requests