22

I am creating Go command-line app and I need to generate some stuff in the current directory (the directory which the user execute the commands from)

to get the pwd I need to use

os.Getwd()

but this give me path like

/Users/s05333/go/src/appcmd

and I need path like this

/Users/s05333/go/src/

which option I've in this case? Omit the last string after the / or there is better way in Go?

07_05_GuyT
  • 2,787
  • 14
  • 43
  • 88

2 Answers2

43

Take a look at the filepath package, particularly filepath.Dir:

wd,err := os.Getwd()
if err != nil {
    panic(err)
}
parent := filepath.Dir(wd)

Per the docs:

Dir returns all but the last element of path, typically the path's directory.

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • 1
    Thanks its working I'll accept the answer in 5 min, can you explain why its working ? :) why dir remove the last path? – 07_05_GuyT Feb 01 '18 at 19:29
  • 5
    I'm not sure I understand the question - it does that because that's its purpose. Read the linked documentation. – Adrian Feb 01 '18 at 19:31
  • 2
    I was surprised to find that this doesn't work in cases where the base directory ends in a trailing slash. `filepath.Dir("/hello/world/")` returns `"hello/world"` rather than the expected `/hello"`. You have to trim trailing slashes before passing the string into `filepath.Dir()` ‍♂️. https://go.dev/play/p/634Yh2U16yQ – weberc2 Apr 21 '22 at 15:48
3

Another option is the path package:

package main
import "path"

func main() {
   s := "/Users/s05333/go/src/appcmd"
   t := path.Dir(s)
   println(t == "/Users/s05333/go/src")
}

https://golang.org/pkg/path#Dir

Zombo
  • 1
  • 62
  • 391
  • 407
  • 9
    The docs specifically warn that the `path` package won't work for filepaths on all operating systems (namely Windows) because it only deals with forward slashes, and to use `path/filepath` instead for OS filesystems. – Travis Britz Mar 19 '21 at 15:59