Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I source a shell script using Go?

Tags:

bash

shell

go

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 !

like image 586
Pith Avatar asked May 01 '15 21:05

Pith


People also ask

Can you use Golang for scripting?

Go's growing adoption as a programming language that can be used to create high-performance networked and concurrent systems has been fueling developer interest in its use as a scripting language.

How do you source a file in shell?

A file is sourced in two ways. One is either writting as source <fileName> or other is writting as . ./<filename> in the command line. When a file is sourced, the code lines are executed as if they were printed on the command line.


1 Answers

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"))
like image 89
Caleb Avatar answered Nov 03 '22 02:11

Caleb