You can execute shell commands using the os/exec standard package:
package main
import (
"log"
"os"
"os/exec"
)
func main() {
cmd := exec.Command(
"ls",
"-la",
)
cmd.Dir = "/"
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatalf("could not run the command: %v", err)
}
}
From the above:
- we define our command with
exec.Commandwith the first argument being the command we want to run (ls). - Then put the rest of the arguments needed by your program (you can have as many as you want)
- we define where we want our program to run with
cmd.Dir, in my case the/ - finally we define how we want the output to be redirected. In my case I do stdout and stderr.
- funally run your command with
cmd.Run