Get the name of the directory where a script is executed

人盡茶涼 提交于 2019-12-23 12:31:10

问题


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

dirname $0

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.

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


回答1:


Get the real path to your script

if [ -L $0 ] ; then
    ME=$(readlink $0)
else
    ME=$0
fi
DIR=$(dirname $ME)



回答2:


if you have realpath installed:

$(dirname $(realpath $0))



回答3:


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

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

python2.6 -c "import os,sys; print os.path.realpath(sys.argv[1])" "$0"

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




回答4:


A simpler solution:

dirname $(readlink -f $0)

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

readlink -f `which java`

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

Finally,

dirname $(readlink -f `which java`)

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



来源:https://stackoverflow.com/questions/3373132/get-the-name-of-the-directory-where-a-script-is-executed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!