How to execute bash code in Golang

Overview

In this course, we are going to learn how to execute a bash codeA bash script is a plain text file that contains a series of commands. from a code in Golang.

Example code

package main
import (
"fmt"
"os/exec"
)
func main() {
app := "echo"
arg0 := "-e"
arg1 := "Hello world"
arg2 := "\n\tfrom"
arg3 := "golang"
cmd := exec.Command(app, arg0, arg1, arg2, arg3)
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
return
}
// Print the output
fmt.Println(string(stdout))
}

Explanation

In the example above:

  • Line 3-6: We import the packages (fmt, os/exec) we need to execute the bash code. We use the fmt to output our result and the exec to run our commands.

  • Line 9-14: We declare and assign a string to variables.

  • Line 16: We assign the cmd variable and run the command by chaining Command() to exec.

Note: Package exec runs external commands. It wraps os.StartProcess to make it easier to remap stdin and stdout, to connect I/O with pipes, and to do other adjustments.

We then access the output() from cmd to obtain the output via commands.

  • Line 25: We obtain the output.

Free Resources