Welcome To Golang By Example

Menu
  • Home
  • Blog
  • Contact Us
  • Support this website
Menu

Execute an OS/System Command in Go (Golang)

Posted on April 13, 2020April 13, 2020 by admin

Table of Contents

  • Overview
  • Code

Overview

os/exec package can be used to trigger any OS or system command from Go. It has two functions which can be used to achieve the same

  • Command – Used to create the cmd object
  • Output – It runs the command and returns the standard output

Code

package main

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

func main() {
    out, err := exec.Command("pwd").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(string(out))
}

Output:

It will output the location of current working directory
  • command
  • go
  • golang
  • system
  • Follow @golangbyexample

    Popular Articles

    Golang Comprehensive Tutorial Series

    All Design Patterns in Go (Golang)

    Slice in golang

    Variables in Go (Golang) – Complete Guide

    OOP: Inheritance in GOLANG complete guide

    Using Context Package in GO (Golang) – Complete Guide

    All data types in Golang with examples

    Understanding time and date in Go (Golang) – Complete Guide

    ©2025 Welcome To Golang By Example | Design: Newspaperly WordPress Theme