Welcome To Golang By Example

Execute shell file from Go (Golang)

Table of Contents

Overview:

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

sample.sh

#!/bin/sh
echo "Triggered from .go file" > out.out
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