bash 检索脚本的父目录
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20196034/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Retrieve parent directory of script
提问by MangO_O
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:
所以uninstall.sh必须这样做:
rm- rf /usr/local/Myapplication
I can retrieve the folder where uninstall resides
我可以检索卸载所在的文件夹
SYMLINKS=$(readlink -f "APP_ROOT="$(dirname "$(dirname "$(readlink -fm "APP_ROOT=$(dirname $(dirname $(readlink -fm my_app_path=$(dirname $(dirname $(readlink -f "cd $(dirname PARENT_DIRECTORY="${PWD%/*}"
)/..
path=$(pwd)
cd - # go back
")))
)))
")")")"
")
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?
但我仍然不确定获得父路径的漂亮方法。我想使用 sed 来卸载此路径的“卸载程序”部分,但是有没有一种优雅的方法来获取 Myapplication 文件夹的路径以将其删除?
Thank you
谢谢
回答by Boldewyn
How about using dirname
twice?
用dirname
两次怎么样?
# dir of script
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )";
# parent dir of that dir
PARENT_DIRECTORY="${DIR%/*}"
The quoting desaster is only necessary to guard against whitespace in paths. Otherwise it would be more pleasing to the eye:
引用 desaster 只需要防止路径中的空格。否则会更顺眼:
##代码##回答by mihai_mandis
Just get the parent of the parent directory:
只需获取父目录的父目录:
##代码##回答by Sergey Fedorov
If you need an absolute path, then you need cd
. Otherwise you can just use $(dirname $0)/..
如果您需要绝对路径,那么您需要cd
. 否则你可以使用$(dirname $0)/..
回答by thom
the ultimate simple way of getting the parent directory path:
获取父目录路径的终极简单方法:
##代码##回答by Joe Goggins
Full path to parent dir of script, i.e. "/usr/local/bin/bla": export PARENT_OF_THIS_SCRIPT=$( cd $(dirname $0) ; pwd -P )
脚本父目录的完整路径,即“/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 )
只是脚本的最新父级,即“bla”: export PARENT_DIR_OF_SCRIPT=$( cd $(dirname $0) ; pwd -P | xargs basename )
回答by Abdennour TOUMI
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 :
我把这个答案作为评论在 2018。但是由于我得到了关于解决方案有效性的很好的反馈,我也将在这里分享:
##代码##回答by Pierre Arlaud
Why don't you simply add ../ at the end of the path?
为什么不简单地在路径末尾添加 ../ ?