Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go: execute bash script

Tags:

bash

go

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!

like image 421
user3918985 Avatar asked Mar 18 '23 11:03

user3918985


2 Answers

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)
}
like image 163
Drew Avatar answered Mar 29 '23 01:03

Drew


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

like image 23
Dario Filipović Avatar answered Mar 29 '23 01:03

Dario Filipović