bash - Go: 执行 bash 脚本

标签 bash go

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

目录结构:

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

  hello.go
  hello.sh

你好.go

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

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

退出状态 127 输出是

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

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

最佳答案

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)
}

关于bash - Go: 执行 bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27765143/

相关文章:

sql - db.Query with sql join error列上的扫描错误

git - 为带有颜色的 git 分支自定义 bash 提示符 (PS1)

bash - unix命令从单词的第一次出现和最后一次出现之间获取行并写入文件

http - 池连接每次都连接?

go - Go中的父子上下文取消顺序

mysql - 为什么 GORM 不能生成外键?

bash - 等到 zip 完全写入然后继续,Bash 脚本

mysql - bash 脚本中 grep 和 mysql 的变量

bash - 如何在 shell 脚本中创建双引号字符串行数组

unit-testing - assert_called_once() 或 assert_called_xyz().... 等效?