我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
当前回答
下面是一个命令,在Bash或zsh下工作,以及是否单独执行或源:
[ -n "$ZSH_VERSION" ] && this_dir=$(dirname "${(%):-%x}") \
|| this_dir=$(dirname "${BASH_SOURCE[0]:-$0}")
它是如何工作的
Fallback 替代操作员:
% x=ok
% echo "${x}"
ok
% echo "${x:-fallback}"
ok
% x=
% echo "${x:-fallback}"
fallback
% y=yvalue
% echo "${x:-$y}"
yvalue
此分類上一篇: %x prompt escape code
接下来,我们将引入即时逃避代码,一个 zsh-only 功能. 在 zsh 中, %x 将扩展到文件的路径,但通常只有在进行即时行扩展时。
% cat apath/test.sh
fpath=%x
echo "${(%)fpath}"
% source apath/test.sh
apath/test.sh
% cd apath
% source test.sh
test.sh
% cat test.sh
echo "${(%):-%x}"
% source test.sh
test.sh
请注意,我们通常会把变量名称放在(%)和(%)之间,但我们留下了白色。
我们可能已经使用打印 -P %x 以获得相同的文件路径,有更少的黑客,但在我们的情况下,我们需要将其作为一个论点转到一个字符串,这将需要一个开始一个新的字符串的顶部:
% cat apath/test.sh
dirname "$(print -P %x)" # $(...) runs a command in a new process
dirname "${(%):-%x}"
% source apath/test.sh
apath
apath
显然,黑客的方式既更有效又更简短。
其他回答
还有另一个选项:
SELF=$(SELF=$(dirname "$0") && bash -c "cd \"$SELF\" && pwd")
echo "$SELF"
它在 macOS 上也起作用,确定了频道路径,并且不会改变当前的目录。
pwd 可以用来找到当前工作目录,而 dirname 可以用来找到特定文件的目录(运行命令为 $0,所以 dirname $0 应该给你当前脚本的目录)。
然而,字体名称给出了字体名称的目录部分,这更有可能与当前工作目录无关,如果你的脚本需要因某种原因更改目录,那么字体名称的输出就会变得毫无意义。
我建议如下:
#!/usr/bin/env bash
reldir="$( dirname -- "$0"; )";
cd "$reldir";
directory="$( pwd; )";
echo "Directory is ${directory}";
这样,你就得到一个绝对的,而不是一个相对的目录。
由于脚本将在一个单独的Bash例子中运行,没有必要恢复工作目录后,但如果你想因某种原因改变你的脚本,你可以轻松地将PWD的值分配给一个变量,在你更改目录之前,用于未来的使用。
雖然只是
cd "$( dirname -- "$0"; )";
解决这个问题的具体场景,我发现有绝对的道路到更有用的一般。
這是Linux的特點,但你可以使用:
SELF=$(readlink /proc/$$/fd/255)
我会用这样的东西:
# 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
这里是JavaScript(即Node.js)的替代方案:
baseDirRelative=$(dirname "$0")
baseDir=$(node -e "console.log(require('path').resolve('$baseDirRelative'))") # Get absolute path using Node.js
echo $baseDir