Welcome To Golang By Example

Execute an OS/System Command in Go (Golang)

Table of Contents

Overview

os/exec package can be used to trigger any OS or system command from Go. It has two functions which can be used to achieve the same

Code

package main

import (
    "fmt"
    "log"
    "os/exec"
)

func main() {
    out, err := exec.Command("pwd").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(out))
}

Output:

It will output the location of current working directory