Source file src/pkg/os/exec/lp_unix.go
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. 4 5 // +build darwin freebsd linux netbsd openbsd 6 7 package exec 8 9 import ( 10 "errors" 11 "os" 12 "strings" 13 ) 14 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") 17 18 func findExecutable(file string) error { 19 d, err := os.Stat(file) 20 if err != nil { 21 return err 22 } 23 if m := d.Mode(); !m.IsDir() && m&0111 != 0 { 24 return nil 25 } 26 return os.ErrPermission 27 } 28 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. 36 37 if strings.Contains(file, "/") { 38 err := findExecutable(file) 39 if err == nil { 40 return file, nil 41 } 42 return "", &Error{file, err} 43 } 44 pathenv := os.Getenv("PATH") 45 for _, dir := range strings.Split(pathenv, ":") { 46 if dir == "" { 47 // Unix shell semantics: path element "" means "." 48 dir = "." 49 } 50 path := dir + "/" + file 51 if err := findExecutable(path); err == nil { 52 return path, nil 53 } 54 } 55 return "", &Error{file, ErrNotFound} 56 }