dsbqfrr098575666
2015-05-01 21:57
浏览 146

如何使用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 !

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

我想使用Go来获取Shell脚本。 理想情况下,以下代码

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

但是,我知道“ source”是bash内置函数,而不是可执行文件。

但是,我发现了一些模仿此功能的方法 Python中的行为:

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

不幸的是,我不知道如何在Go中进行翻译。 有人有想法吗?

谢谢!

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

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"))
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongliao9233 2018-01-18 17:00

    I have recently added such a utility function to my shell/bash Golang library:

    https://godoc.org/mvdan.cc/sh/shell#SourceFile

    For example, you could do:

    vars, err := shell.SourceFile("foo.sh")
    if err != nil { ... }
    fmt.Println(vars["URL"].Value)
    // http://the.url/value
    

    It's decently safe, because it never actually calls bash nor any other program. It parses the shell script, then interprets it. But when interpreting, it has a whitelist of what files the script can open and what programs the script can execute.

    The interpreter also has a context.Context, so you can set a timeout if you want to be protected against forever loops or other bad code.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题