Skip to content

Instantly share code, notes, and snippets.

@andyeff
Created April 11, 2024 13:15
Show Gist options
  • Save andyeff/3371d74ee028404485a1e983b6127972 to your computer and use it in GitHub Desktop.
Save andyeff/3371d74ee028404485a1e983b6127972 to your computer and use it in GitHub Desktop.
Where did my app start from
package main
import (
"fmt"
"log"
"os"
"path/filepath"
)
func main() {
// Returns the PWD of the shell invoking the binary
curdir, err := os.Getwd()
if err != nil {
log.Fatalf("fatal error: %s\n", err)
}
fmt.Printf("the working dir is %s\n", curdir)
// This one isn't great
curdir2 := filepath.Dir(os.Args[0])
fmt.Printf("the working dir is %s\n", curdir2)
// Also returns the PWD of the shell invoking the binary
curdir3, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
log.Fatalf("fatal error: %s\n", err)
}
fmt.Printf("the working dir is %s\n", curdir3)
// This will get the path of the binary itself
curdir4, err := os.Executable()
if err != nil {
log.Fatalf("fatal error: %s\n", err)
}
curdir4 = filepath.Dir(curdir4)
fmt.Printf("the working dir is %s\n", curdir4)
}
@andyeff
Copy link
Author

andyeff commented Apr 11, 2024

curdir / curdir3 are useful for getting the path of where the shell or whatever is when it launches the binary.

curdur4 is useful for finding out the path of where the binary itself is.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment