0

I can get the current directory and the name of the current .go file but if i build a .exe from the file with go build then i still get the .go name.

.../Project/Test/testfile.go

After building testfile.go with go build i have these:

1) .../Project/Test/testfile.go

2) .../Project/Test/main.exe

When i execute main.exe i get testfile But i want to get the main name after executing main.exe

package main

import (
    "errors"
    "fmt"
    "path/filepath"
    "runtime"
    "strings"
)

func GetFileName() string {
    _, fpath, _, ok := runtime.Caller(0)
    if !ok {
        err := errors.New("failed to get filename")
        panic(err)
    }
    filename := filepath.Base(fpath)
    filename = strings.Replace(filename, ".go", "", 1)
    return filename
}

func main() {
    fmt.Print(GetFileName())
}
0_o
  • 570
  • 6
  • 18
  • 4
    You could use `os.Args[0]` to obtain the executable name – CanobbioE Feb 14 '20 at 08:11
  • @CanobbioE Sorry didn't know it is that easy. U can write a answer so i mark it as solved – 0_o Feb 14 '20 at 08:19
  • 2
    See also [os.Executable](https://golang.org/pkg/os/#Executable). Args may not be what you want, but since you haven't told us what you really want we can't recommend one or the other. – Peter Feb 14 '20 at 08:24
  • @Peter I want to get the 'executable' name in any situation. With or without a argument or in any path. Also i think always args[0] contains the executable name like in c#. Do you recomment anything better? – 0_o Feb 14 '20 at 09:44

1 Answers1

3

The os package provides os.Args[0] to obtain the executable name, or if you want the whole path you could use os.Executable, as @Peter has suggested

CanobbioE
  • 222
  • 2
  • 11
  • Args does *not* contain the name of the executable. It's merely the first argument, i.e. "whatever I typed on the shell" (\*waves hands\*). It can be the name of a symlink pointing to the executable, for instance. – Peter Feb 14 '20 at 08:33