dongyushen9063
2014-09-14 14:25
浏览 204

从Golang执行Bash脚本

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.).

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.

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

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:

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

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

Any ideas how to achieve this?

图片转代码服务由CSDN问答提供 功能建议

我正在尝试找出一种从Golang执行脚本(.sh)文件的方法。 我发现了几种简单的执行命令的方法(例如os / exec),但是我要执行的是执行整个sh文件(该文件设置了变量等)。 < p>使用标准的os / exec方法似乎并不简单:尝试输入“ ./script.sh”并将脚本内容加载到字符串中都不能作为exec函数的参数。

例如,这是我要从Go执行的sh文件:

  OIFS = $ IFS; 
IFS =“  ,“; 
 
#在此处填写您的详细信息
dbname = testDB 
host = localhost:27017 
collection = testCollection 
exportTo = .. / csv / 
 
#获取以逗号分隔的键列表。 通过查看集合中的第一个文档并获得他的一组键
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`; 
#现在将mongoexport与一组密钥一起使用,以将集合导出到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()
如果err!= nil {
 log.Fatal(err)
} 
 fmt.Printf(“输出为%s \  n“,out)
   
 
 

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

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • douqi3064 2014-09-14 14:33
    已采纳

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

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

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

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

    cmd := exec.Command("/bin/sh", mongoToCsvSH)
    
    评论
    解决 无用
    打赏 举报
查看更多回答(1条)

相关推荐 更多相似问题