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.

GoSecurity Boundaries

Code

snippet
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

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.