gpt4 book ai didi

bash - 如何使用 Go 获取 shell 脚本?

转载 作者:IT王子 更新时间:2023-10-29 00:40:31 24 4
gpt4 key购买 nike

我想使用 Go 获取 shell 脚本。理想情况下的代码

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

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

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

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

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

谢谢!

最佳答案

您可以在使用 exec 运行程序时设置环境变量:

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

如果您确实需要源代码,那么您可以通过 bash 运行命令:

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

查看此库以获得功能更全的工作流程: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"))

关于bash - 如何使用 Go 获取 shell 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29995741/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com