Welcome To Golang By Example

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

Execute shell file from Go (Golang)

Posted on February 22, 2020February 22, 2020 by admin

Table of Contents

  • Overview:
  • Code:

Overview:

os/exec package can be used to trigger any OS command from Go. The same can be used for triggering .sh file.

  • First, create a sample.sh file in the same directory. Make sure it either starts with #!/bin/sh or #!/bin/bash

sample.sh

#!/bin/sh
echo "Triggered from .go file" > out.out
  • Make this sample.sh file executable
chmod +x sample.sh

Code:

Create a below main.go file in the same directory

package main

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

func main() {
    out, err := exec.Command("/bin/sh", "sample.sh").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(out)
}

Output:

A out.out file will be created in the same directory
  • bash
  • 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