Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the parent path

Tags:

go

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?

like image 970
07_05_GuyT Avatar asked Feb 01 '18 19:02

07_05_GuyT


2 Answers

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.

like image 88
Adrian Avatar answered Oct 10 '22 06:10

Adrian


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

like image 43
Zombo Avatar answered Oct 10 '22 06:10

Zombo