-2

I am trying to write a script to process some code in a GOPATH. The code may be nested multiple directories deep.

I'll be running my script in an environment where GOPATH doesn't exist.

What's a simple way in shell to find the GOPATH from a nested directory inside the GOPATH?

It works if I do something like this

GOAPTH=$(dirname $(dirname $(dirname $(dirname $(pwd)))))

or

GOPATH=$(cd ../../../../; pwd)

But it requires me to have to know how many levels I am nested.

Drew LeSueur
  • 19,185
  • 29
  • 89
  • 106
  • What should be the characteristics of a directory being `GOPATH`? – iBug May 12 '18 at 13:38
  • Good point. For me my GOPATH is always called `go`. So my solution was to find a directory named `go` that has `src` in it. – Drew LeSueur May 12 '18 at 13:42
  • Any particular reason for needing to compute the path as opposed to just setting it in environment and reading it from there? Seems to me this path won’t change very frequently. – Timir May 12 '18 at 14:03
  • @Timir yea that's probably a better way. – Drew LeSueur May 12 '18 at 15:17

1 Answers1

-1

With some help from bash: get path to parent directory by name

I came up with this:

GOPATH="${PWD%/go/src/*}/go"

It takes the current working directory path, trims anything at and after /go/src, and then ads /go to the end.

It seems like a simple way to do it.

Drew LeSueur
  • 19,185
  • 29
  • 89
  • 106