Search This Blog

2013-05-14

获得脚本的当前执行路径

以前做过一个Java项目,需要脚本来启动程序,我写了.bat跟.sh文件,但是有个问题,必须到脚本所在目录去执行,否则找不到需要的jar包,有些开源项目的脚本也有这个问题。

我希望脚本能在任意目录执行,这就需要获得脚本的路径,然后确定jar包所在的位置,加上绝对路径。后来看了Ant跟Tomcat的启动脚本(写得很长,很复杂)。获得脚本执行路径只需要很少的代码,命令如下:
Windows:
%~dp0

Unix/Linux/MacOSX:
$(cd -P -- "$(dirname -- "$0")" && pwd -P)

1 参考资料

http://svn.apache.org/repos/asf/lenya/branches/trunk-rework-pubconf/tools/bin/ant.bat
rem %~dp0 is expanded pathname of the current script under NT
set DEFAULT_ANT_HOME=%~dp0..
http://svn.apache.org/repos/asf/lenya/branches/trunk-rework-pubconf/tools/bin/ant
Re: How to get the dirname of a bash shell script inside the script? - Author: Database Administrator - dbaspot.com
Which directory is that bash script in? - Author: chris - www.electrictoolbox.com

=文章版本=

20130513

No comments:

Post a Comment