Golang Run Command Line

The Go/Golang codes below executed successfully in Ubuntu.

package main

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

func main() {
app := "date"

arg0 := "-d"
arg1 := "3 Jan 2009 12:34:56 AM"
arg2 := "+%Y-%m-%d %H:%M:%S"

cmd := exec.Command(app, arg0, arg1, arg2)
stdout, err := cmd.Output()

if err != nil {
panic(err)
}

fmt.Print(strings.TrimSpace(string(stdout)))
}

If the commands involves pipe ( | ), I prefer to have it written in bash script and have Golang just execute the bash script.

< Back to all the stories I had written

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store