Golang Run Command Line

Kevin FOO
Feb 26, 2021

--

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.

func Bash(cmd string) string{
strUUID := uuid.New().String()
strPath := fmt.Sprintf("/tmp/%s.sh", strUUID)
ioutil.WriteFile(strPath, []byte(cmd), 0744)
out,err := exec.Command("/bin/bash", strPath).CombinedOutput()
check(err)
os.Remove(strPath)
return string(out[:])
}

uuid is available at github.com/google/uuid

< Back to all the stories I had written

--

--

Kevin FOO
Kevin FOO

Written by Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.

No responses yet