我正在try 找出一种从Golang执行脚本(.sh)文件的方法.我已经找到了几种执行命令的简单方法(例如os/exec),但我想要做的是执行整个sh文件(该文件设置变量等).
为此,使用标准的os/exec方法似乎并不简单:try 输入"./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;
从围棋项目:
out, err := exec.Command(mongoToCsvSH).Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("output is %s\n", out)
其中mongoToCsvSH可以是sh的路径,也可以是实际内容-两者都不起作用.
有什么办法可以做到这一点吗?