Skip to content

Instantly share code, notes, and snippets.

@kevsmith
Last active November 13, 2024 17:02
Show Gist options
  • Save kevsmith/926178595a84c5c93ac4a11aad3e4cc4 to your computer and use it in GitHub Desktop.
Save kevsmith/926178595a84c5c93ac4a11aad3e4cc4 to your computer and use it in GitHub Desktop.
Dynamically discover executable path at runtime
package main
import (
"fmt"
"os"
"path/filepath"
)
func executableLocation() (string, string, error) {
// 0th arg traditionally contains name of executable as invoked by the user
// Split executable name into directory path and filename parts
exeDir, exeFile := filepath.Split(os.Args[0])
// Clean the directory path and convert it to an absolute path
// This handles cases where a relative path reference is used
// such as "./foo" or "../foo"
absoluteExeDir, err := filepath.Abs(filepath.Clean(exeDir))
// Return error if absolute path construction fails
if err != nil {
return "", "", err
}
return absoluteExeDir, exeFile, nil
}
func main() {
exeDir, exeFileName, err := executableLocation()
if err != nil {
panic(err)
}
fmt.Printf("Executable dir: %s\nExecutable filename: %s\n", exeDir, exeFileName)
}
> go build -o discover main/main.go
> ./discover
Executable dir: /Users/kesmit/repos/experiments/discover
Executable filename: discover
> go run main/main.go
Executable dir: /var/folders/1c/19j1cgwx2ng1gjxj5rypmkwh0000gp/T/go-build3431073968/b001/exe
Executable filename: main
>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment