我如何找到一个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 代替。

其他回答

选择的答案非常好,我把我的解决方案发送给任何人寻找更短的替代方案,这些解决方案仍然涉及来源、执行、完整路径、相对路径和同步链接,最后,这将在 macOS 上工作,因为不能假设GNU的核心路径的阅读链接版本可用。

GOTCHA是它不使用Bash,但它很容易在Bash脚本中使用,虽然OP没有在解决方案的语言上设置任何限制,但它可能是最好的,大多数人已经留在Bash世界中。

PHP 可在 macOS 默认情况下,并安装在其他平台上,但不一定是默认情况下. 我意识到这是一个缺点,但我会留下这个在这里,任何人来自搜索引擎,无论如何。

export SOURCE_DIRECTORY="$(php -r 'echo dirname(realpath($argv[1]));' -- "${BASH_SOURCE[0]}")"

我会用这样的东西:

# 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”字母:

#!/usr/bin/env bash

echo "The script you are running has basename $( basename -- "$0"; ), dirname $( dirname -- "$0"; )";
echo "The present working directory is $( pwd; )";

使用 pwd 单独不会工作,如果您不从它包含的目录中运行脚本。

[matt@server1 ~]$ pwd
/home/matt
[matt@server1 ~]$ ./test2.sh
The script you are running has basename test2.sh, dirname .
The present working directory is /home/matt
[matt@server1 ~]$ cd /tmp
[matt@server1 tmp]$ ~/test2.sh
The script you are running has basename test2.sh, dirname /home/matt
The present working directory is /tmp

這是解決方案 e-satis 和 3bcdnlklvc04a 在他們的答案中指出的輕微改訂:

SCRIPT_DIR=''
pushd "$(dirname "$(readlink -f "$BASH_SOURCE")")" > /dev/null && {
    SCRIPT_DIR="$PWD"
    popd > /dev/null
}

这应该在他们列出的所有情况下仍然有效。

这将防止一个失败的冲动之后的Popd. 感谢控制台。

如果你的Bash脚本是一个同链接,那么这就是如何做到这一点:

#!/usr/bin/env bash

dirn="$(dirname "$0")"
rl="$(readlink "$0")";
exec_dir="$(dirname $(dirname "$rl"))";
my_path="$dirn/$exec_dir";
X="$(cd $(dirname ${my_path}) && pwd)/$(basename ${my_path})"

X 是包含您的 Bash 脚本的目录(原始文件,而不是同链接)。我向上帝发誓这项工作,这是我唯一知道如何正确地做到这一点。