MangO_O
MangO_O

Reputation: 423

Retrieve parent directory of script

I'm working on an uninstaller script to delete the parent folder where the script is installed.

/usr/local/Myapplication/Uninstaller/uninstall.sh

So uninstall.sh has to do this:

rm- rf /usr/local/Myapplication

I can retrieve the folder where uninstall resides

SYMLINKS=$(readlink -f "$0")
UNINSTALL_PATH=$(dirname "$SYMLINKS")

But I'm still unsure of the pretty way to get the parent path. I thought of using sed to demove the "Uninstaller" part of this path, but is there an elegant way to get the path to Myapplication folder to delete it?

Thank you

Upvotes: 19

Views: 28696

Answers (8)

Abdull
Abdull

Reputation: 27832

As $0 can have suprising behavior, here is a solution using BASH_SOURCE[0]:

#/bin/bash

PARENT_DIR=$(dirname $(dirname $(readlink -f "${BASH_SOURCE[0]}")))

Upvotes: 1

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93183

I put this answer as comment at 2018. But since I got a great feedback about the effectiveness of the solution, I will share it here as well :

# dir of script 
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )";
# parent dir of that dir
PARENT_DIRECTORY="${DIR%/*}"

Upvotes: 5

Boldewyn
Boldewyn

Reputation: 82734

How about using dirname twice?

APP_ROOT="$(dirname "$(dirname "$(readlink -fm "$0")")")"

The quoting desaster is only necessary to guard against whitespace in paths. Otherwise it would be more pleasing to the eye:

APP_ROOT=$(dirname $(dirname $(readlink -fm $0)))

Upvotes: 29

Joe Goggins
Joe Goggins

Reputation: 1338

Full path to parent dir of script, i.e. "/usr/local/bin/bla": export PARENT_OF_THIS_SCRIPT=$( cd $(dirname $0) ; pwd -P )

Just the most recent parent of script, i.e. "bla": export PARENT_DIR_OF_SCRIPT=$( cd $(dirname $0) ; pwd -P | xargs basename )

Upvotes: 2

thom
thom

Reputation: 2332

the ultimate simple way of getting the parent directory path:

PARENT_DIRECTORY="${PWD%/*}" 

Upvotes: 2

Sergey Fedorov
Sergey Fedorov

Reputation: 2169

If you need an absolute path, then you need cd. Otherwise you can just use $(dirname $0)/..

cd $(dirname $0)/..
path=$(pwd)
cd - # go back

Upvotes: 4

mihai_mandis
mihai_mandis

Reputation: 1658

Just get the parent of the parent directory:

my_app_path=$(dirname $(dirname $(readlink -f "$0")))

Upvotes: 8

Pierre Arlaud
Pierre Arlaud

Reputation: 4133

Why don't you simply add ../ at the end of the path?

Upvotes: 1

Related Questions