Golang Exec Package

Executing shell commands, script files, and executables in Go

In this article, we are going to learn how to execute external shell commands, script files and executable files from a Go program using built-in os/exec package

Uday Hiwarale
Feb 9 · 8 min read
(source: unsplash.com)

LookPath function

func LookPath(file string) (string, error)
(https://play.golang.org/p/TR3NzK3kV8p)

Cmd Structure

type Cmd struct {
// path of a program or executable
Path string
// arguments to invoke program or executable with
Args []string
// environment variables for the execution
Env []string
// current working directory of the execution
Dir string
// standard input for the execution
Stdin io.Reader
// standard output for the execution
Stdout io.Writer
// standard error for the execution
Stderr io.Writer
// Process is the underlying process, once started
Process *os.Process
}
(https://play.golang.org/p/Ln1Eg2dP-Dp)
$ go run go-cmd.go
/usr/local/go/bin/go version

Run method

(https://play.golang.org/p/xaT15EES0TF)
go version go1.13.5 darwin/amd64

Start and Wait methods

func (c *Cmd) Start() error
func (c *Cmd) Wait() error
#!/usr/bin/env bash
sleep 3
echo "Hello!!!!"
(https://play.golang.org/p/1huGMKR8N6G)
......
299991
299992
299993
299994
299995
299996
299997
299998
299999
Hello!!!!

Command function

func Command(name string, arg ...string) *Cmd
(https://play.golang.org/p/6881UDyztph)
go version go1.13.5 darwin/amd64

Output method

func (c *Cmd) Output() ([]byte, error)
(https://play.golang.org/p/V53jbtH_1v3)
go version go1.13.5 darwin/amd64

CombinedOutput method

func (c *Cmd) CombinedOutput() ([]byte, error)


RunGo

A place to find introductory Go Programming Language tutorials and learning resources. Like my other tutorials on Web Development, RunGo publication features important Go articles with deep dive into core of the language with examples and sample code.

Uday Hiwarale

Written by

IITI (2014) • Software Developer • India | Follow: http://github.com/thatisuday | Ask: thatisuday@gmail.com

RunGo

RunGo

A place to find introductory Go Programming Language tutorials and learning resources. Like my other tutorials on Web Development, RunGo publication features important Go articles with deep dive into core of the language with examples and sample code.

More From Medium

More from RunGo

More from RunGo

3.8K

More from RunGo

2.6K

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade