In this course, we are going to learn how to execute a
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))}
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
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.