从Golang执行Bash脚本

orc*_*man 24 bash go

我试图找出一种从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;
Run Code Online (Sandbox Code Playgroud)

来自Go计划:

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

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

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

One*_*One 33

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

  1. #!/bin/sh(或#!/bin/bash等)启动它.

  2. 你必须让它可执行,也就是说chmod +x script.

如果您不想这样做,那么您将必须执行/bin/sh脚本的路径.

cmd := exec.Command("/bin/sh", mongoToCsvSH)
Run Code Online (Sandbox Code Playgroud)

  • 谢谢。这似乎有效。但是现在我有一个不同的问题 - 尽管脚本需要大约 1 分钟才能运行,但程序不会等待它完成运行。所以在没有实际编写导出的情况下继续执行......有什么想法吗? (2认同)
  • 我们可以在上面的例子中将参数传递给 mongoToCsvSH 吗? (2认同)

小智 13

这对我有用

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

  • 当 /path/to/file.sh 需要参数时添加参数怎么样? (2认同)

Eva*_*van 5

您需要执行/bin/sh并将脚本本身作为参数传递。