Go: Current working directory
-
Use
os.Executable
to find the path name for the executable that started the current process. -
Use
filepath.Dir
in packagepath/filepath
to extract the path's directory.
path, err := os.Executable()
if err != nil {
log.Printf(err)
}
dir := filepath.Dir(path)
fmt.Println(path) // For example /home/user/main
fmt.Println(dir) // For example /home/user
Warning: There is no guarantee that the path is still pointing to the correct executable. If a symlink was used to start the process, depending on the operating system, the result might be the symlink or the path it pointed to. If a stable result is needed, path/filepath.EvalSymlinks
might help.
Comments
Be the first to comment!