dongyushen9063 2014-09-14 14:25
浏览 242
已采纳

从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?

  • 写回答

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

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)
  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。