Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get parent directory of shell script's directory [duplicate]

Tags:

bash

shell

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?

like image 495
Alexander Mills Avatar asked Nov 25 '16 05:11

Alexander Mills


People also ask

How do I go to parent directory in shell?

You can go back to the parent directory of any current directory by using the command cd .. , as the full path of the current working directory is understood by Bash . You can also go back to your home directory (e.g. /users/jpalomino ) at any time using the command cd ~ (the character known as the tilde).

How can I get the source directory of a bash script from within the script itself?

You can use $BASH_SOURCE : #!/usr/bin/env bash scriptdir="$( dirname -- "$BASH_SOURCE"; )"; Note that you need to use #!/bin/bash and not #!/bin/sh since it's a Bash extension.


2 Answers

I believe the answer is

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

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

like image 102
Alexander Mills Avatar answered Oct 12 '22 03:10

Alexander Mills


Run dirname twice (nested).

~$ dirname $PWD
/home
~$ dirname `dirname $PWD`
/
~$ 
like image 24
Sharad Avatar answered Oct 12 '22 03:10

Sharad