1 // Copyright 2010 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // +build darwin freebsd linux netbsd openbsd
15 // ErrNotFound is the error resulting if a path search failed to find an executable file.
16 var ErrNotFound
= errors
.New("executable file not found in $PATH")
18 func findExecutable(file
string) error
{
19 d
, err
:= os
.Stat(file
)
23 if m
:= d
.Mode(); !m
.IsDir() && m
&0111 != 0 {
26 return os
.ErrPermission
29 // LookPath searches for an executable binary named file
30 // in the directories named by the PATH environment variable.
31 // If file contains a slash, it is tried directly and the PATH is not consulted.
32 func LookPath(file
string) (string, error
) {
33 // NOTE(rsc): I wish we could use the Plan 9 behavior here
34 // (only bypass the path if file begins with / or ./ or ../)
35 // but that would not match all the Unix shells.
37 if strings
.Contains(file
, "/") {
38 err
:= findExecutable(file
)
42 return "", &Error
{file
, err
}
44 pathenv
:= os
.Getenv("PATH")
46 return "", &Error
{file
, ErrNotFound
}
48 for _
, dir
:= range strings
.Split(pathenv
, ":") {
50 // Unix shell semantics: path element "" means "."
53 path
:= dir
+ "/" + file
54 if err
:= findExecutable(path
); err
== nil {
58 return "", &Error
{file
, ErrNotFound
}