我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
当前回答
我会用这样的东西:
# Retrieve the full pathname of the called script
scriptPath=$(which $0)
# Check whether the path is a link or not
if [ -L $scriptPath ]; then
# It is a link then retrieve the target path and get the directory name
sourceDir=$(dirname $(readlink -f $scriptPath))
else
# Otherwise just get the directory name of the script path
sourceDir=$(dirname $scriptPath)
fi
其他回答
在我看来,最合适的解决方案是:
"$( cd "$( echo "${BASH_SOURCE[0]%/*}" )"; pwd )"
使用 dirname、 readlink 和 basename 最终会导致兼容性问题,所以如果可能的话最好避免。
我用三种不同的处决尝试了追踪。
echo $(实际上是 $_)
. application # /correct/path/to/dir or /path/to/temporary_dir
bash application # /path/to/bash
/PATH/TO/application # /correct/path/to/dir
echo $(相当于 $(相当于 $0))
. application # failed with `realpath: missing operand`
bash application # /correct/path/to/dir
/PATH/TO/application # /correct/path/to/dir
echo $(相当于 $BASH_SOURCE)
$BASH_SOURCE 基本上与 ${BASH_SOURCE[0]} 相同。
. application # /correct/path/to/dir
bash application # /correct/path/to/dir
/PATH/TO/application # /correct/path/to/dir
只有$(实际上是$BASH_SOURCE)似乎是可靠的。
没有百分之百可携带和可靠的方式来要求一个路径到当前的脚本目录,特别是在不同背景,如Cygwin,MinGW,MSYS,Linux等之间,这个问题没有正确和完全解决在Bash的年龄。
在源命令的情况下,我建议用这样的东西取代源命令:
function include()
{
if [[ -n "$CURRENT_SCRIPT_DIR" ]]; then
local dir_path=... get directory from `CURRENT_SCRIPT_DIR/$1`, depends if $1 is absolute path or relative ...
local include_file_path=...
else
local dir_path=... request the directory from the "$1" argument using one of answered here methods...
local include_file_path=...
fi
... push $CURRENT_SCRIPT_DIR in to stack ...
export CURRENT_SCRIPT_DIR=... export current script directory using $dir_path ...
source "$include_file_path"
... pop $CURRENT_SCRIPT_DIR from stack ...
}
从现在开始,使用包括(...)是基于以前的CURRENT_SCRIPT_DIR在你的脚本。
我自己最接近这一点的实施: https://sourceforge.net/p/tacklelib/tacklelib/HEAD/tree/trunk/bash/tacklelib/bash_tacklelib https://github.com/andry81/tacklelib/tree/trunk/bash/tacklelib/bash_tacklelib
(搜索 tkl_include 函数)
我认为最简单的答案是原始变量的参数扩展:
#!/usr/bin/env bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
echo "opt1; original answer: $DIR"
echo ''
echo "opt2; simple answer : ${BASH_SOURCE[0]%/*}"
它应该产生产量如:
$ /var/tmp/test.sh
opt1; original answer: /var/tmp
opt2; simple answer : /var/tmp
变量/参数扩展 ${BASH_SOURCE[0]%/*}”似乎更容易保持。
目前的任何解决方案都没有工作,如果在目录名称结束时有任何新字符 - 它们将被命令替代器切断。 要在此周围工作,您可以在命令替代器中添加一个非新字符,然后切断该字符:
dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd && echo x)"
dir="${dir%x}"
這保護兩個非常常見的情況:事故和破壞. 一個劇本不應該以不可預測的方式失敗,只是因為有人,在某個地方,做了一個 mkdir $ '\n'.