问题描述
如何获取脚本的目录路径位于 中那个脚本?
How do I get the path of the directory in which a Bash script is located, inside that script?
例如,我想使用一个Bash脚本作为另一个应用程序的启动器。我想将工作目录更改为Bash脚本所在的目录,因此我可以对目录中的文件进行操作,如下所示:
For instance, let's say I want to use a Bash script as a launcher for another application. I want to change the working directory to the one where the Bash script is located, so I can operate on the files in that directory, like so:
$ ./application
推荐答案
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
一个线程,无论从哪里被调用,都将为您提供脚本的完整目录名。
is a useful one-liner which will give you the full directory name of the script no matter where it is being called from.
只要路径的最后一个组件用来查找脚本不是一个符号链接(目录链接可以)。如果您还想解决脚本本身的任何链接,您需要一个多行解决方案:
It will work as long as the last component of the path used to find the script is not a symlink (directory links are OK). If you also want to resolve any links to the script itself, you need a multi-line solution:
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
SOURCE="$(readlink "$SOURCE")"
[[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
done
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
最后一个使用别名的任何组合, source
, bash -c
,符号链接等。
This last one will work with any combination of aliases, source
, bash -c
, symlinks, etc.
小心:如果您在运行此代码段之前将 cd
转到另一个目录,结果可能不正确!另外,请注意。
Beware: if you cd
to a different directory before running this snippet, the result may be incorrect! Also, watch out for $CDPATH
gotchas.
要了解它的工作原理,请尝试运行这种更详细的形式:
To understand how it works, try running this more verbose form:
#!/bin/bash
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink
TARGET="$(readlink "$SOURCE")"
if [[ $TARGET == /* ]]; then
echo "SOURCE '$SOURCE' is an absolute symlink to '$TARGET'"
SOURCE="$TARGET"
else
DIR="$( dirname "$SOURCE" )"
echo "SOURCE '$SOURCE' is a relative symlink to '$TARGET' (relative to '$DIR')"
SOURCE="$DIR/$TARGET" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located
fi
done
echo "SOURCE is '$SOURCE'"
RDIR="$( dirname "$SOURCE" )"
DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
if [ "$DIR" != "$RDIR" ]; then
echo "DIR '$RDIR' resolves to '$DIR'"
fi
echo "DIR is '$DIR'"
它将打印如下:
SOURCE './scriptdir.sh' is a relative symlink to 'sym2/scriptdir.sh' (relative to '.')
SOURCE is './sym2/scriptdir.sh'
DIR './sym2' resolves to '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
DIR is '/home/ubuntu/dotfiles/fo fo/real/real1/real2'
这篇关于从内部获取Bash脚本的源目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!