Exec LookPath Searches PATH For Binaries
Resolve command names through exec.LookPath, handle the ErrNotFound path, and see why names containing separators bypass the PATH search.
Code
package main
import (
"fmt"
"os/exec"
)
func main() {
// LookPath 按 PATH 目录逐个查找 binaries,找到返回完整路径
path, err := exec.LookPath("go")
if err == nil {
fmt.Println("found:", path)
} else {
fmt.Println("go not on PATH:", err)
}
// 名字不存在:返回 exec.ErrNotFound 包装的错误
_, missing := exec.LookPath("definitely-not-a-real-binary-xyz")
fmt.Println("missing is error:", missing != nil)
// 名字带分隔符时跳过 PATH 搜索,按相对/绝对路径直查:
// ./tool 永远不会意外命中 PATH 里的程序,防住当前目录注入
_, local := exec.LookPath("./definitely-not-here")
fmt.Println("explicit relative is error:", local != nil)
}How this snippet works
The snippet is organized around the function main.
Watch out for
- Zero outside dependencies — every API used comes from the runtime.
Putting it to use
Entry signature: func main()
The file’s output announces its steps: found:, go not on PATH:, missing is error:.
Core lines
_, missing := exec.LookPath("definitely-not-a-real-binary-xyz")
Interactive Tools for This Topic
Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.bcrypt Cost EstimatorEstimate bcrypt cost factor latency and brute-force resistance, and get a recommended cost for your target hash time and attacker throughput.CORS Header Policy DebuggerSimulate browser CORS preflight and credential policies against server response headers to pinpoint blocked origins, methods, or headers and fix them.CSP Header BuilderBuild a Content-Security-Policy header from per-directive sources, skipping empty ones and rejecting a blanket wildcard.
FAQ
- What does Exec LookPath Searches PATH For Binaries print when run?
- Invoke the file as-is — the `found:`, `go not on PATH:`, `missing is error:` prefixes identify which step printed each line.
Report a problem with this exampleOpens a pre-filled issue on GitHub.