Check if executable is in the path with go

· 269 words · 2 minute read

To check if an executable is in the path we use the exec package and its exported LookPath() function.

Docs and Resources: ##


  • output of go doc exec.LookPath:
1package exec // import "os/exec"
2func LookPath(file string) (string, error)

LookPath searches for an executable named file in the directories named by the PATH environment variable. If file contains a slash, it is tried directly and the PATH is not consulted. LookPath also uses PATHEXT environment variable to match a suitable candidate. The result may be an absolute path or a path relative to the current directory.

Snippet ##

 1// declare file as in package main
 2package main
 4// import formatting and executable packages
 5import (
 6	"fmt"
 7	"os/exec"
10// checks if executable 'e' is in path
11func checkIfExecInPath(e string) bool {
12	// ignore output, only use error
13	_, err := exec.LookPath(e)
14	// return true if error nil, else false
15	return err == nil
18func main() {
19	fmt.Println(checkIfExecInPath("git")) // returns: true
20	fmt.Println(checkIfExecInPath("gut")) // returns: false


For a realworld application of this, take a look at my git auto sync project, which uses git to periodically update a repository. For this to work it checks if git is installed before running:

1// taken from:
2if !checkForGit(conf) {
3	log.Fatalln("[FATAL ERROR] 'git' executable not found, gas requires git to work properly - exiting.")
1// taken from:
2func checkForGit(conf Config) bool {
3	DebugLog(conf, "checking for git executable in path...")
4	_, err := exec.LookPath("git")
5	return err == nil