从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的路径,也可以是实际内容的路径-两者都不起作用。

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

一对一

为了使Shell脚本可直接运行,您必须:

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

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章