3 回答

TA貢獻1815條經驗 獲得超13個贊
不能,環(huán)境變量只能向下傳遞,不能向上傳遞。你正在嘗試做后者。
您的流程樹:
`--- shell
`--- go program
|
`--- other program
go 程序必須將環(huán)境變量傳遞給 shell,以便其他程序可以訪問它。
您可以做的是程序喜歡ssh-agent做的事情:返回一個字符串,該字符串可以被解釋為設置一個環(huán)境變量,然后可以由 shell 對其進行評估。
例如:
func main() {
fmt.Println("WHAT='is your name'")
}
運行它會給你:
$ ./goprogram
WHAT='is your name'
評估打印的字符串會給你想要的效果:
$ eval `./goprogram`
$ echo $WHAT
is your name

TA貢獻1872條經驗 獲得超4個贊
其他答案嚴格正確,但是您可以自由執(zhí)行 golang 代碼,將環(huán)境變量的任意值填充到 go 創(chuàng)建的輸出文件中,然后返回到您執(zhí)行 go 二進制文件的父環(huán)境中,然后將 go 的輸出文件源到從你的 go 代碼中計算出可用的 env 變量......這可能是你的 go 代碼 write_to_file.go
package main
import (
"io/ioutil"
)
func main() {
d1 := []byte("export whodunit=calculated_in_golang\n")
if err := ioutil.WriteFile("/tmp/cool_file", d1, 0644); err != nil {
panic(err)
}
}
現在將上面的 write_to_file.go 編譯成二進制文件write_to_file……這是一個 bash 腳本,它可以作為父文件執(zhí)行上面的二進制文件
#!/bin/bash
whodunit=aaa
if [[ -z $whodunit ]]; then
echo variable whodunit has no value
else
echo variable whodunit has value $whodunit
fi
./write_to_file # <-- execute golang binary here which populates an exported var in output file /tmp/cool_file
curr_cool=/tmp/cool_file
if [[ -f $curr_cool ]]; then # if file exists
source /tmp/cool_file # shell distinguishes sourcing shell from executing, sourcing does not cut a subshell it happens in parent env
fi
if [[ -z $whodunit ]]; then
echo variable whodunit still has no value
else
echo variable whodunit finally has value $whodunit
fi
這是執(zhí)行上述 shell 腳本的輸出
variable whodunit has value aaa
variable whodunit finally has value calculated_in_golang
- 3 回答
- 0 關注
- 224 瀏覽
添加回答
舉報