如何使用Go来源shell脚本?

Pit*_*ith 4 bash shell go

我想使用Go来源shell脚本.理想情况下,以下代码

cmd := exec.Command("/bin/bash", "source", file.Name())
Run Code Online (Sandbox Code Playgroud)

但是,我知道"source"是一个bash内置函数,而不是可执行文件.

但是,我发现了一些在Python中模仿这种行为的方法:

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

不幸的是,我不知道如何在Go中翻译它.有没有人有想法?

谢谢 !

Cal*_*leb 5

使用exec以下命令运行程序时可以设置环境变量:

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

如果你真的需要源,那么你可以通过bash运行你的命令:

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

查看此库以获得更全面的工作流程:https://github.com/progrium/go-basher.

更新:这是一个修改当前环境的示例:

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"))
Run Code Online (Sandbox Code Playgroud)