Golang Code

Run System Commands & Binary Files

· 114 words · 1 minute read #cmd #command #system #run #execute #output #binary

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.

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.

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!