Thursday, September 8, 2016

Golang and Shell Script : Execute sh file from Go file and vice-versa.

We will see here today, executing a Go file from Shell script file and vice-versa.

Don't know, how to create and run a shell script file ?
Shell script file name : hello_sh.sh
Content of hello_sh.sh :

echo "Hello, I am inside 'hello_sh.sh' file."
echo "Now, I am going to call 'hello_go.go' file. The output: "
go run hello_go.go


Hello world ! program in Golang.
Go file name : hello_go.go
Content of hello_go.go :


package main
import (
        "bytes"
        "fmt"
        "log"
        "os/exec"
        "strings"
)
func main() {
        fmt.Printf("Hello, I am from 'hello_go.go' file.");
        fmt.Printf("\nNow, I am going to execute 'hello_sh.sh' file\n");
        cmd := exec.Command("bash", "hello_sh.sh");
        cmd.Stdin = strings.NewReader("");
        var out bytes.Buffer;
        cmd.Stdout = &out;
        err := cmd.Run();
        if err != nil {
                log.Fatal(err);
        }
        fmt.Printf("Output \n",out.String());
}


*For beginner change the file name "hello_sh.sh" and  "hello_go.go" according to your requirement.
*For advanced programmer, try this recursion and you can comment your output below.


-Thank you




1 comment: