Golang: System Call
System Call Tutorial
To make a system call, use
import "os/exec"
First, build your command. example:
var cmd = exec.Command(cmdName, arg1, arg2)
Each arg should not contain any space.
then, you have several choices how you want to run it. The main choices are:
cmd.Output()
- Run it, wait, get output.
cmd.Run()
- Run it, wait for it to finish.
cmd.Start()
-
Run it, don't wait.
err = cmd.Wait()
to get result.
if you need to change dir before running the command, use
os.Chdir(path)
package main // example of calling shell command // cd to a given dir // call ls -al // print its output import "fmt" import "os" import "os/exec" func main() { var dirToRun = "/Users/xah/web/" var err = os.Chdir(dirToRun) if err != nil { panic(err) } var cmdName = "ls" var cmd = exec.Command(cmdName, "-a", "-l") output, err := cmd.Output() if err != nil { panic(err) } fmt.Printf("%v\n", string(output)) }