How to Execute Shell Commands in Go Using os/exec

You can execute shell commands using the os/exec standard package:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
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.Command with 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
Last updated on Oct 14, 2024 11:46 +0300
comments powered by Disqus
Citizix Ltd
Built with Hugo
Theme Stack designed by Jimmy