9

I have a shell script here:

/node_modules/.bin/exec.sh

in the exec.sh script, I want to obtain the path of the directory's parent directory that the script is contained in (not pwd/cwd!). I can obtain the containing directory like so:

`dirname $0`

which will yield:

/node_modules/.bin

but I am looking to get at one directory higher, I just want to get

/node_modules

I am having trouble searching for the answer, my guess is:

`dirname $1`

but just a guess, not sure if that's right at all. Can anyone give an explanation of how to do this and how it works?

Alexander Mills
  • 1
  • 80
  • 344
  • 642
  • no, not at all, this has nothing to do with cwd/pwd – Alexander Mills Nov 25 '16 at 05:29
  • @AlexanderMills It has everything to do with that. Get the parent directory of your target. Then get the parent directory of *that* directory. – Ouroborus Nov 25 '16 at 05:30
  • 1
    no, it has to do with the directory that contains the script, not the current working directory or present working directory, they could be very different...imagine you execute the script like so ../../exec.sh, thanks though – Alexander Mills Nov 25 '16 at 05:33
  • @AlexanderMills I actually had selected the wrong answer from the list of possible duplicates. I retracted my close vote for now. – Michael Kohl Nov 25 '16 at 05:59
  • 1
    you can use parameter expansion.. `p='/node_modules/.bin/exec.sh'; echo "${p%/*/*}"` – Sundeep Nov 25 '16 at 07:45
  • @Ouroborus..."Get the parent directory of your target. Then get the parent directory of that directory." (Where target is the bash script). What does that have to do with PWD/CWD again? – Alexander Mills Nov 25 '16 at 09:24

2 Answers2

10

Run dirname twice (nested).

~$ dirname $PWD
/home
~$ dirname `dirname $PWD`
/
~$ 
Sharad
  • 5,301
  • 2
  • 16
  • 30
5

I believe the answer is

$(dirname $(dirname "$0"))

don't forget about the double-quotes around "$0"

Alexander Mills
  • 1
  • 80
  • 344
  • 642