从 Golang 执行 Bash 脚本

新手上路,请多包涵

我正在尝试找出一种从 Golang 执行脚本 (.sh) 文件的方法。我找到了几个执行命令的简单方法(例如 os/exec),但我想要做的是执行整个 sh 文件(文件设置变量等)。

为此使用标准的 os/exec 方法似乎并不简单:尝试输入“./script.sh”和将脚本的内容加载到字符串中都不能作为 exec 函数的参数。

例如,这是一个我想从 Go 执行的 sh 文件:

 OIFS=$IFS;
IFS=",";

# fill in your details here
dbname=testDB
host=localhost:27017
collection=testCollection
exportTo=../csv/

# get comma separated list of keys. do this by peeking into the first document in the collection and get his set of keys
keys=`mongo "$host/$dbname" --eval "rs.slaveOk();var keys = []; for(var key in db.$collection.find().sort({_id: -1}).limit(1)[0]) { keys.push(key); }; keys;" --quiet`;
# now use mongoexport with the set of keys to export the collection to csv
mongoexport --host $host -d $dbname -c $collection --fields "$keys" --csv --out $exportTo$dbname.$collection.csv;

IFS=$OIFS;

来自 Go 程序:

 out, err := exec.Command(mongoToCsvSH).Output()
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("output is %s\n", out)

其中 mongoToCsvSH 可以是 sh 的路径或实际内容 - 两者都不起作用。

任何想法如何实现这一目标?

原文由 orcaman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.5k
2 个回答

为了使您的 shell 脚本可以直接运行,您必须:

  1. #!/bin/sh 开始(或 #!/bin/bash 等)。

  2. 您必须使其可执行,又名 chmod +x script

如果您不想这样做,则必须使用脚本路径执行 /bin/sh

 cmd := exec.Command("/bin/sh", mongoToCsvSH)

原文由 OneOfOne 发布,翻译遵循 CC BY-SA 3.0 许可协议

这对我有用

func Native() string {
    cmd, err := exec.Command("/bin/sh", "/path/to/file.sh").Output()
    if err != nil {
    fmt.Printf("error %s", err)
    }
    output := string(cmd)
    return output
}

原文由 Richard Bright 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题