bash 获取执行脚本的目录名称

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

Get the name of the directory where a script is executed

linuxbashscripting

提问by rodnower

I have some script, that uses files in directories around it. It uses

我有一些脚本,它使用它周围目录中的文件。它用

dirname 
if [ -L 
$(dirname $(realpath 
python2.6 -c "import os,sys; print os.path.realpath(sys.argv[1])" "
dirname $(readlink -f 
readlink -f `which java`
)
"
))
] ; then ME=$(readlink
dirname $(readlink -f `which java`)
) else ME=##代码## fi DIR=$(dirname $ME)

command. It should work from any directory where I run this script, but when I run a symbolic link that points to that script I get the path of symbolic link. So I get the output of dirname rather than the path of the script itself.

命令。它应该在我运行这个脚本的任何目录中工作,但是当我运行一个指向该脚本的符号链接时,我得到了符号链接的路径。所以我得到的是 dirname 的输出而不是脚本本身的路径。

Any one know a way to get the path of where the script is run?

任何人都知道一种获取脚本运行路径的方法吗?

采纳答案by jmz

Get the real path to your script

获取脚本的真实路径

##代码##

回答by knittl

if you have realpathinstalled:

如果您已realpath安装:

##代码##

回答by loevborg

Unless I misunderstand you, the problem should be the same as the one in: How do you normalize a file path in Bash?

除非我误解你的意思,否则问题应该与:如何在 Bash 中规范化文件路径中的问题相同

An option not mentioned there is the following python one-liner:

一个没有提到的选项是以下 python 单行:

##代码##

Finally, remember to use double quotes around "$0".

最后,请记住在“$0”周围使用双引号。

回答by Alexandre Santos

A simpler solution:

一个更简单的解决方案:

##代码##

Tested with on Ubuntu 14.04: which javareturns /usr/bin/java, which is a symbolic link.

在 Ubuntu 14.04 上测试: which java返回/usr/bin/java,这是一个符号链接。

##代码##

Returns /usr/lib/jvm/java-8-oracle/jre/bin/java

退货 /usr/lib/jvm/java-8-oracle/jre/bin/java

Finally,

最后,

##代码##

Returns /usr/lib/jvm/java-8-oracle/jre/bin, which is the folder under which "java" is located.

返回/usr/lib/jvm/java-8-oracle/jre/bin,即“java”所在的文件夹。