Run System Commands & Binary Files

· 132 words · 1 minute read

Within Go, like other languages, we have the ability to call external binaries. These allow us to do all sorts of things, but in our example we’re just going to print out our go version by calling our copy (located in /usr/local/go/bin on my computer).

The Command function within the os/exec package will allow us to do this. It accepts at least one string - the name of the command/binary you’re trying to run - followed by any number of strings for it’s parameters.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
package main

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

func main() {

    // Print Go Version
    cmdOutput, err := exec.Command("go", "version").Output()
    if err != nil {
        log.Fatal(err)
    }

    fmt.Printf("%s", cmdOutput)
}

Image of Author Edd Turtle

Author:  Edd Turtle

Edd is the Lead Developer at Hoowla, a prop-tech startup, where he spends much of his time working on production-ready Go and PHP code. He loves coding, but also enjoys cycling and camping in his spare time.

See something which isn't right? You can contribute to this page on GitHub or just let us know in the comments below - Thanks for reading!