从 Golang 执行 Bash 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25834277/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 21:40:15  来源:igfitidea点击:

Executing a Bash Script from Golang

bashgo

提问by orcaman

I am trying to figure out a way to execute a script (.sh) file from Golang. I have found a couple of easy ways to execute commands (e.g. os/exec), but what I am looking to do is to execute an entire sh file (the file sets variables etc.).

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

Using the standard os/exec method for this does not seem to be straightforward: both trying to input "./script.sh" and loading the content of the script into a string do not work as arguments for the exec function.

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

for example, this is an sh file that I want to execute from Go:

例如,这是我想从 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;

from the Go program:

来自 Go 程序:

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

where mongoToCsvSH can be either the path to the sh or the actual content - both do not work.

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

Any ideas how to achieve this?

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

回答by OneOfOne

For your shell script to be directly runnable you have to:

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

  1. Start it with #!/bin/sh(or #!/bin/bash, etc).

  2. You have to make it executable, aka chmod +x script.

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

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

If you don't want to do that, then you will have to execute /bin/shwith the path to the script.

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

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

回答by Evan

You need to execute /bin/shand pass the script itself as an argument.

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