bash Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/bash/ Sat, 22 Feb 2020 07:37:05 +0000 en-US hourly 1 https://wordpress.org/?v=6.8.1 https://i0.wp.com/golangbyexamples.com/wp-content/uploads/2021/05/cropped-go_border-1.png?fit=32%2C32&ssl=1 bash Archives - Welcome To Golang By Example https://vikasboss.github.io/tag/bash/ 32 32 159787465 Execute shell file from Go (Golang) https://vikasboss.github.io/execute-shell-file-golang/ https://vikasboss.github.io/execute-shell-file-golang/#respond Sat, 22 Feb 2020 04:12:33 +0000 https://vikasboss.github.io/?p=1419 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...

The post Execute shell file from Go (Golang) appeared first on Welcome To Golang By Example.

]]>
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

The post Execute shell file from Go (Golang) appeared first on Welcome To Golang By Example.

]]>
https://vikasboss.github.io/execute-shell-file-golang/feed/ 0 1419