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

有什么办法可以做到这一点吗?

推荐答案

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

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

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

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

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

Go相关问答推荐

JWT库返回及时无效的令牌有效

如何创建两个连接的io.ReadWriteClosers以用于测试目的

Go协议缓冲区导入问题

如何使用Promela建模语言对Golang RWLock进行建模

迭代字符串并用映射值替换原始字符串中的值的惯用方法

Cypher 查找(多个)最低 node

通过 Terraform 中的 MapNestedAtribute 进行迭代

为什么 mux.Vars() 返回空的 map[]

Golang prometheus:有没有办法衡量出站请求的指标?

如何解决我的 Go 聊天应用程序中 cookie 未在本地主机端口之间传输的问题?

你如何在 Golang 代码中测试 filepath.Abs​​ 失败?

Golang 中的泛型类型转换

Apache Beam 左加入 Go

函数实现接口时的模式名称是什么?

如何使用 Docker 引擎 SDK 和 Golang 运行 docker 挂载卷

Protobuf.Any - 从 json.RawMessage 解组

如何在golang中按字符a对字符串数组进行排序

在删除级联时无法在 Gorm 中按预期工作

Golang prometheus 显示自定义指标

有没有办法在 golang 中定义可索引类型?