我如何找到一个Bash脚本位于该脚本内部的目录的路径?

我想用Bash脚本作为另一个应用程序的启动器,我想将工作目录更改为Bash脚本所在的目录,所以我可以在该目录中的文件上运行,如下:

$ ./application

当前回答

$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 代替。

其他回答

我想评论上面的答案(我如何从脚本本身中获取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

正如代码所表明的那样,一旦您获得脚本的绝对路径,则您可以使用命令命名以获得目录的路径。

大多数答案都不会处理通过相对路径连接的文件,不是单线或不处理BSD(Mac)。

HERE=$(cd "$(dirname "$BASH_SOURCE")"; cd -P "$(dirname "$(readlink "$BASH_SOURCE" || echo .)")"; pwd)

首先, cd 到 bash 的概念的脚本的目录. 然后 readlink 文件,以查看它是否是一个 symlink (相对或其他), 如果是这样, cd 到该目录. 否则, cd 到当前目录(需要保持事物一个单线)。 然后 echo 当前目录通过 pwd。

你可以添加 - 到CD和阅读链接的论点,以避免名为选项的目录问题,但我不在乎大多数目的。

你可以看到完整的解释与图像在这里:

https://www.binaryphile.com/bash/2020/01/12/determining-the-location-of-your-script-in-bash.html

我会用这样的东西:

# 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

您可以从脚本本身中获取一个Bash脚本的源目录,随之而来:

script_path=$(dirname "$(readlink -f "$0")")"/"
echo "$script_path"

样品输出:

/home/username/desktop/

尝试使用:

real=$(realpath "$(dirname "$0")")