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)

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
$ go run go-cmd.go
/usr/local/go/bin/go version

Run method

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!!!!"

Command function

func Command(name string, arg ...string) *Cmd
go version go1.13.5 darwin/amd64

Output method

func (c *Cmd) Output() ([]byte, error)
go version go1.13.5 darwin/amd64

CombinedOutput method

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


A place to find introductory Go programming language…

Uday Hiwarale

Written by

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



A place to find introductory Go programming language tutorials and learning resources. In this publication, we will learn Go in an incremental manner, starting from beginner lessons with mini examples to more advanced lessons. — (Created by @thatisuday)

More From Medium

More from RunGo

More from RunGo

More from RunGo


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