我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
我如何找到一个Bash脚本位于该脚本内部的目录的路径?
我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:
$ ./application
当前回答
我想评论上面的答案(我如何从脚本本身中获取Bash脚本的源目录?),但没有足够的声誉来做到这一点。
我在两年前在苹果的文档网站上找到了一个解决方案: https://developer.apple.com/library/archive/documentation/OpenSource/Conceptual/ShellScripting/AdvancedTechniques/AdvancedTechniques.html。
#!/bin/sh
# Get an absolute path for the poem.txt file.
POEM="$PWD/../poem.txt"
# Get an absolute path for the script file.
SCRIPT="$(which $0)"
if [ "x$(echo $SCRIPT | grep '^\/')" = "x" ] ; then
SCRIPT="$PWD/$SCRIPT"
fi
正如代码所表明的那样,一旦您获得脚本的绝对路径,则您可以使用命令命名以获得目录的路径。
其他回答
我会用这样的东西:
# 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
$0 不是一个可靠的方式来获得当前的脚本路径. 例如,这是我的.xprofile:
#!/bin/bash
echo "$0 $1 $2"
echo "${BASH_SOURCE[0]}"
# $dir/my_script.sh &
cd /tmp && ~/.xprofile && 来源 ~/.xprofile
/home/puchuu/.xprofile
/home/puchuu/.xprofile
-bash
/home/puchuu/.xprofile
因此,请使用 BASH_SURCE 代替。
這是Linux的特點,但你可以使用:
SELF=$(readlink /proc/$$/fd/255)
目前的任何解决方案都没有工作,如果在目录名称结束时有任何新字符 - 它们将被命令替代器切断。 要在此周围工作,您可以在命令替代器中添加一个非新字符,然后切断该字符:
dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd && echo x)"
dir="${dir%x}"
這保護兩個非常常見的情況:事故和破壞. 一個劇本不應該以不可預測的方式失敗,只是因為有人,在某個地方,做了一個 mkdir $ '\n'.
此单行在 Cygwin 上工作,即使脚本已被从 Windows 称为 bash -c <script>:
set mydir="$(cygpath "$(dirname "$0")")"