Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the path to the executable

Tags:

path

go

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).

like image 329
topskip Avatar asked Aug 23 '12 11:08

topskip


People also ask

Where is the executable path in Linux?

type Command The type command can not only show the path of a Linux command, but it can also tell if the target is built-in, a function, an alias, or an external executable.

What is Windows executable path?

The Windows System PATH tells your PC where it can find specific directories that contain executable files. ipconfig.exe , for example, is found in the C:\Windows\System32 directory, which is a part of the system PATH by default.

How do I find the path in Windows?

Alternatively follow the instructions below to open the command prompt (even faster than on Windows Server). Go to the destination folder and click on the path (highlights in blue). type cmd. Command prompt opens with the path set to your current folder.


2 Answers

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) } 
like image 66
Dobrosław Żybort Avatar answered Nov 10 '22 08:11

Dobrosław Żybort


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) } 
like image 40
iamdual Avatar answered Nov 10 '22 07:11

iamdual