Go:执行 bash 脚本

use*_*985 4 bash go

如何从 Go 程序执行 bash 脚本?这是我的代码:

目录结构:

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

  hello.go
  hello.sh
Run Code Online (Sandbox Code Playgroud)

你好去

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

当我运行 hello.go 并调用相关路由时,我在控制台上得到了这个:

exit status 127 output is

我期待 ["a", "b", "c"]

我知道 SO: Executing a Bash Script from Golang上有一个类似的问题,但是,我不确定我的路径是否正确。将不胜感激帮助!

Dre*_*rew 5

exec.Command() 返回一个可用于其他命令的结构,如 Run

如果您只是在寻找命令的输出,请尝试以下操作:

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)
}
Run Code Online (Sandbox Code Playgroud)