Retrieve parent directory of script

2019-04-28 10:01发布

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

标签: bash shell unix
6条回答
迷人小祖宗
2楼-- · 2019-04-28 10:21

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
查看更多
做个烂人
3楼-- · 2019-04-28 10:39

Just get the parent of the parent directory:

my_app_path=$(dirname $(dirname $(readlink -f "$0")))
查看更多
我命由我不由天
4楼-- · 2019-04-28 10:40

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

查看更多
ら.Afraid
5楼-- · 2019-04-28 10:41

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 )

查看更多
乱世女痞
6楼-- · 2019-04-28 10:43

the ultimate simple way of getting the parent directory path:

PARENT_DIRECTORY="${PWD%/*}" 
查看更多
虎瘦雄心在
7楼-- · 2019-04-28 10:45

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)))
查看更多
登录 后发表回答