我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
当前回答
在完整的披露中,......(我找到了这个使者的变量部分)以及在Rich’s sh的技巧中,我也在我自己的答案的披露下披露了他的页面的相关部分。
具体的:
雖然不是嚴格 POSIX 到目前為止, realpath 是一個 GNU 核心應用程式自 2012 年 全公開:我從未聽到它之前,我注意到它在 info coreutils TOC 和立即思考 [連結] 問題,但使用下列功能,如顯示應該可靠,(現在 POSIXLY?),我希望,有效地提供其呼叫者一個絕對來源的 $0:
% _abs_0() {
> o1="${1%%/*}"; ${o1:="${1}"}; ${o1:=`realpath -s "${1}"`}; eval "$1=\${o1}";
> }
% _abs_0 ${abs0:="${0}"} ; printf %s\\n "${abs0}"
/no/more/dots/in/your/path2.sh
另一方面,你可以这样做:
ps ww -fp $$ | grep -Eo '/[^:]*'"${0#*/}"
eval "abs0=${`ps ww -fp $$ | grep -Eo ' /'`#?}"
试试这:
func () {
body here
eval "$1=\${foo}"
}
foo='hello ; rm -rf /'
dest=bar
eval "$dest=$foo"
当然,下面的版本是完全安全的:
foo='hello ; rm -rf /'
dest=bar
eval "$dest=\$foo"
其他回答
这在Bash 3.2中工作:
path="$( dirname "$( which "$0" )" )"
如果您在 $PATH 中有 ~/bin 目录,则在此目录中有 A. 它源于 ~/bin/lib/B. 您知道所包含的目录与原始目录相对,在 lib 子目录中,但不是与用户当前目录相对。
以以下方式解决问题(A内部):
source "$( dirname "$( which "$0" )" )/lib/B"
无论用户在哪里,还是他/她如何呼叫脚本,这总是会工作。
function getScriptAbsoluteDir { # fold>>
# @description used to get the script path
# @param $1 the script $0 parameter
local script_invoke_path="$1"
local cwd=`pwd`
# absolute path ? if so, the first character is a /
if test "x${script_invoke_path:0:1}" = 'x/'
then
RESULT=`dirname "$script_invoke_path"`
else
RESULT=`dirname "$cwd/$script_invoke_path"`
fi
} # <<fold
这是我唯一能以可靠的方式说的话:
SCRIPT_DIR=$(dirname $(cd "$(dirname "$BASH_SOURCE")"; pwd))
此单行在 Cygwin 上工作,即使脚本已被从 Windows 称为 bash -c <script>:
set mydir="$(cygpath "$(dirname "$0")")"
$(dirname "$(readlink -f "$BASH_SOURCE")")