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: ##

Info

  • 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
 3
 4// import formatting and executable packages
 5import (
 6	"fmt"
 7	"os/exec"
 8)
 9
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
16}
17
18func main() {
19	fmt.Println(checkIfExecInPath("git")) // returns: true
20	fmt.Println(checkIfExecInPath("gut")) // returns: false
21}

Tip

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: https://github.com/xNaCly/git-auto-sync/blob/579276f62a0d30b45a3c2b01634bfff9703ce1ea/main.go#L14-L16
2if !checkForGit(conf) {
3	log.Fatalln("[FATAL ERROR] 'git' executable not found, gas requires git to work properly - exiting.")
4}
1// taken from: https://github.com/xNaCly/git-auto-sync/blob/579276f62a0d30b45a3c2b01634bfff9703ce1ea/util.go#L101-L105
2func checkForGit(conf Config) bool {
3	DebugLog(conf, "checking for git executable in path...")
4	_, err := exec.LookPath("git")
5	return err == nil
6}