[英]Programatically and reliably retrieve the path to the go executable in container without 'which' with Go
How can I retrieve the path to the go
binary in a container that does not have which
programatically ? 我怎样才能检索到的路径,
go
在没有一个容器二进制which
编程 ?
One option would be to execute which go
as follows: 一种选择是要执行
which go
,如下所示:
bytes, err := exec.Command("which", "go").Output()
However, I would like to not depend on which
being available. 但是,我不想依赖于可用的
which
。 Does go provide any in-built mechanism to retrieve this and if not, what is the alternative apart from having the user pass in the path themselves? go是否提供任何内置机制来检索此内容,如果没有,除了让用户自己通过路径之外,还有什么其他选择?
From the man page of which
: 从手册页的
which
:
Which takes one or more arguments.
需要一个或多个参数。 For each of its arguments it prints to stdout the full path of the executables that would have been executed when this argument had been entered at the shell prompt.
对于它的每个参数,它都会打印以输出在shell提示符下输入此参数时将要执行的可执行文件的完整路径。 It does this by searching for an executable or script in the directories listed in the environment variable PATH using the same algorithm as bash(1).
它通过使用与bash(1)相同的算法在环境变量PATH中列出的目录中搜索可执行文件或脚本来完成此任务。
Go's os/exec.LookPath
function is very close to this functionality: Go的
os/exec.LookPath
函数非常接近此功能:
LookPath searches for an executable named file in the directories named by the PATH environment variable.
LookPath在PATH环境变量命名的目录中搜索可执行文件(名为可执行文件)。 If file contains a slash, it is tried directly and the PATH is not consulted.
如果文件包含斜杠,则直接尝试,不查询PATH。 The result may be an absolute path or a path relative to the current directory.
结果可能是绝对路径或相对于当前目录的路径。
Use path/filepath.Abs
if you need a guaranteed absolute path. 如果需要保证的绝对路径,请使用
path/filepath.Abs
。
I don't expect this to be the best answer, but it is one that I just found. 我不希望这是最好的答案,但这是我刚刚找到的答案。 I was hoping for more of a go-specific one, but in the meantime type in linux is a default built-in one available in bash and sh (alpine).
我一直希望有更多特定于go的版本,但与此同时linux中的类型是bash和sh(高山)可用的默认内置类型 。
You can test this yourself by running type type
which yields: 您可以通过运行以下
type type
来自己进行测试:
type is a shell builtin
类型是内置的shell
The usage in go
would look like this: go
的用法如下所示:
b, err := exec.Command("type", "go").Output()
if err != nil {
/* 'type' is not available on the O/S */
}
goPath := strings.TrimPrefix(strings.TrimSuffix(string(b), "\n"), "go is ")
The reason the Trim
functions are required is because the output would look like this: 需要
Trim
函数的原因是因为输出看起来像这样:
go is /usr/local/go/bin/go\\n
go是/ usr / local / go / bin / go \\ n
This isn't the nicest way of going about it, but it works. 这不是解决问题的最好方法,但是它可行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.