Shell Expansion (Command substitution) in Golang

孤街浪徒 提交于 2021-02-19 03:53:07

问题


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?


回答1:


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}.



来源:https://stackoverflow.com/questions/49001114/shell-expansion-command-substitution-in-golang

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!