4

How do I execute a bash script from my Go program? Here's my code:

Dir Structure:

/hello/
  public/
    js/
      hello.js
  templates
    hello.html

  hello.go
  hello.sh

hello.go

cmd, err := exec.Command("/bin/sh", "hello.sh")
  if err != nil {
    fmt.Println(err)
}

When I run hello.go and call the relevant route, I get this on my console:

exit status 127 output is

I'm expecting ["a", "b", "c"]

I am aware there is a similar question on SO: Executing a Bash Script from Golang, however, I'm not sure if I'm getting the path correct. Will appreciate help!

3 Answers 3

5

exec.Command() returns a struct that can be used for other commands like Run

If you're only looking for the output of the command try this:

package main

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

func main() {
    out, err := exec.Command("date").Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("The date is %s\n", out)
}
Sign up to request clarification or add additional context in comments.

Comments

2

You can also use CombinedOutput() instead of Output(). It will dump standard error result of executed command instead of just returning error code. See: How to debug "exit status 1" error when running exec.Command in Golang

Comments

0

Check the example at http://golang.org/pkg/os/exec/#Command

You can try by using an output buffer and assigning it to the Stdout of the cmd you create, as follows:

var out bytes.Buffer
cmd.Stdout = &out

You can then run the command using

cmd.Run() 

If this executes fine (meaning it returns nil), the output of the command will be in the out buffer, the string version of which can be obtained with

out.String()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.