How to execute bash code in Golang
Overview
In this course, we are going to learn how to execute a
Example code
package mainimport ("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 outputfmt.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 thefmtto output our result and theexecto run our commands. -
Line 9-14: We declare and assign a
stringto variables. -
Line 16: We assign the
cmdvariable and run the command by chainingCommand()toexec.
Note: Package
execruns external commands. It wrapsos.StartProcessto make it easier to remapstdinandstdout, 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.