Skip to content

Instantly share code, notes, and snippets.

@arxdsilva
Last active January 6, 2025 19:29
Show Gist options
  • Save arxdsilva/4f73d6b89c9eac93d4ac887521121120 to your computer and use it in GitHub Desktop.
Save arxdsilva/4f73d6b89c9eac93d4ac887521121120 to your computer and use it in GitHub Desktop.
How to get the current working directory in golang
package main
// More info on Getwd()
// https://golang.org/src/os/getwd.go
//
import(
"os"
"fmt"
"log"
)
func main() {
dir, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
fmt.Println(dir)
}
@Yegorov
Copy link

Yegorov commented Jan 6, 2025

If you would like to find the current directory name - then you can extend it further.

// More info on Getwd()
// https://golang.org/src/os/getwd.go
// 
import(
  "os" 
  "fmt"
  "log"
)

func main() {
  dir, err := os.Getwd()
	if err != nil {
		log.Fatal(err)
	}
  fmt.Println(dir)
  var ss [] string
  if runtime.GOOS == "windows" {
		ss = strings.Split(dir, "\\")
	} else {
		ss = strings.Split(dir, "/")
	}

	currentDirName:= ss[len(ss)-1]

	fmt.Println("Current Directory Name: ", currentDirName)
}

For split path it is probably better to use os.PathSeparator constant

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