Find the path to the executable

23,432

Solution 1

Use package osext.

It's providing function Executable() that returns an absolute path to the current program executable. It's portable between systems.

Online documentation

package main

import (
    "github.com/kardianos/osext"
    "fmt"
)

func main() {
    filename, _ := osext.Executable()
    fmt.Println(filename)
}

Solution 2

You can use os.Executable for getting executable path on Go 1.8 or above version.

import (
    "os"
    "path"
    "log"
)

func main() {
    ex, err := os.Executable()
    if err != nil { log.Fatal(err) }
    dir := path.Dir(ex)
    log.Print(dir)
}

Solution 3

This is not go-specific (unless the go "standard library" contains some function to do it), and there is no portable solution. For solutions on some common platforms, see e.g. How do I find the location of the executable in C? or Finding current executable's path without /proc/self/exe .

Share:
23,432
topskip
Author by

topskip

I like to write software, for example for database publishing https://github.com/speedata/publisher/. Sometimes I work on my book about Go (in German).

Updated on July 31, 2020

Comments

  • topskip
    topskip almost 4 years

    I compile a program with Go for various platforms and run it by calling a relative path or just by its name (if it is in the PATH variable).

    Is it possible to find out where the executable is?

    Say, my program is called "foo(.exe)". I can run ./foo, foo (if it's in the PATH), ../../subdir/subdir/foo.

    I have tried to use os.Args[0] and I guess I should check if the program name contains something different besides "foo". If yes, use filepath.Abs, if no, use (I can't find the function name, there is a function that looks through the PATH to check where the program is).

  • Felix Rabe
    Felix Rabe over 9 years
    It would be great if this also worked with go run executable.go.
  • Dobrosław Żybort
    Dobrosław Żybort over 9 years
    You can always make request on package issue tracker: bitbucket.org/kardianos/osext/issues But I don't know if it will be possible.
  • topskip
    topskip about 9 years
    @DobrosławŻybort I use osext in a current project an it works fine.
  • topskip
    topskip about 7 years
    Good to know, I'll try it and remove the stuff I had before.
  • deFreitas
    deFreitas about 7 years
    This is a native solution that works for me
  • deFreitas
    deFreitas about 7 years
    This is another native solution that works for me