dsbqfrr098575666 2015-05-01 21:57
浏览 163
已采纳

如何使用Go来获取shell脚本?

I want to source shell scripts using Go. Ideally the following code

cmd := exec.Command("/bin/bash", "source", file.Name())

but, I know that "source" is a bash built-in function, not an executable.

However, I have found some ways to mimic this behavior in Python:

http://pythonwise.blogspot.fr/2010/04/sourcing-shell-script.html

Unfortunately, I don't know how to translate this in Go. Does anyone have an idea ?

Thanks !

  • 写回答

2条回答 默认 最新

  • douna2633 2015-05-01 22:18
    关注

    You can set environmental variables when running a program using exec:

    cmd := exec.Command("whatever")
    cmd.Env = []string{"A=B"}
    cmd.Run()
    

    If you really need source then you can run your command through bash:

    cmd := exec.Command("bash", "-c", "source " + file.Name() + " ; echo 'hi'")
    cmd.Run()
    

    Check out this library for a more full-featured workflow: https://github.com/progrium/go-basher.

    Update: Here's an example that modifies the current environment:

    package main
    
    import (
        "bufio"
        "bytes"
        "io/ioutil"
        "log"
        "os"
        "os/exec"
        "strings"
    )
    
    func main() {
        err := ioutil.WriteFile("example_source", []byte("export FOO=bar; echo $FOO"), 0777)
        if err != nil {
            log.Fatal(err)
        }
    
        cmd := exec.Command("bash", "-c", "source example_source ; echo '<<<ENVIRONMENT>>>' ; env")
        bs, err := cmd.CombinedOutput()
        if err != nil {
            log.Fatalln(err)
        }
        s := bufio.NewScanner(bytes.NewReader(bs))
        start := false
        for s.Scan() {
            if s.Text() == "<<<ENVIRONMENT>>>" {
                start = true
            } else if start {
                kv := strings.SplitN(s.Text(), "=", 2)
                if len(kv) == 2 {
                    os.Setenv(kv[0], kv[1])
                }
            }
        }
    }
    
    log.Println(os.Getenv("FOO"))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划