Search code examples
shellgocommand-substitution

Shell Expansion (Command substitution) in Golang


Go has the support for variable expansion, for example:

os.ExpandEnv("test-${USER}")`

>> "test-MyName"

But is there a way of expanding executables, as the way the shell behaves?

Something like

os.ExpandExecutable("test-$(date +%H:%M)")

>> "test-18:20"

I cannot find an equivalent method for this, is there an elegant way of doing this instead of manually extracting the placeholders out, executing and then replacing them?


Solution

  • There's no built in function for this, but you can write a function and pass it to os.Expand().

    package main
    
    import (
        "fmt"
        "os"
        "os/exec"
        "strings"
    )
    
    func RunProgram(program string) string {
        a := strings.Split(program, " ")
        out, err := exec.Command(a[0], a[1:]...).Output()
        if err != nil {
            panic(err)
        }
        return string(out)
    }
    

    // You then call it as:

    func main() {
        s := os.Expand("test-${date +%H:%M}", RunProgram)
        fmt.Print(s)
    }
    

    This outputs:

    test-13:09
    

    Note that os.Expand() expects curly braces, i.e. ${command args args args}.