bash 获取shell脚本目录的父目录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40798249/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 15:27:30  来源:igfitidea点击:

Get parent directory of shell script's directory

bashshell

提问by Alexander Mills

I have a shell script here:

我这里有一个shell脚本:

/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:

在 exec.sh 脚本中,我想获取该脚本所在目录的父目录的路径(不是 pwd/cwd!)。我可以像这样获取包含目录:

`dirname 
/node_modules/.bin
`

which will yield:

这将产生:

/node_modules

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

但我希望获得更高的一个目录,我只想得到

`dirname `

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

我在寻找答案时遇到了麻烦,我的猜测是:

~$ dirname $PWD
/home
~$ dirname `dirname $PWD`
/
~$ 

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?

但只是一个猜测,不确定这是否正确。谁能解释一下如何做到这一点以及它是如何工作的?

回答by Sharad

Run dirname twice (nested).

运行 dirname 两次(嵌套)。

$(dirname $(dirname "##代码##"))

回答by Alexander Mills

I believe the answer is

我相信答案是

##代码##

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

不要忘记“$0”周围的双引号