如何从bash中的源脚本中获取源bash-dir



我想把所有常用函数放在一个"CCD_ 1";然后使用CCD_ 2命令对其进行调用。

这是sourcing脚本:/tmp/main/sourcing_test.sh

#!/bin/bash
source /tmp/sourced/included_by_other_shell_script.sh
echo "test_dir: $test_dir"

这是sourced脚本:/tmp/sourced/included_by_other_shell_script.sh

#!/bin/bash
get_bash_script_dir() {
printf "%s" "${BASH_SOURCE[0]}"
}
test_dir="$(get_bash_script_dir)"

运行来源测试:

/tmp/main/sourcing_test.sh

这是输出:

root@test:~# /tmp/main/sourcing_test.sh
test_dir: /tmp/sourced/included_by_other_shell_script.sh

以下是预期输出:

root@test:~# /tmp/main/sourcing_test.sh
test_dir: /tmp/main

如何在公共函数"中获取源bash-dir;get_bash_script_dir()";?

使用"${BASH_SOURCE[-1]}""${BASH_SOURCE[2]}"而不是included_by_other_shell_script.sh0。

说明:BASH_SOURCE是一个数组,在当前调用堆栈中的每一层都有一个条目(source被视为函数调用)。因此,在您的功能范围内:

  • CCD_ 13是函数的源文件/tmp/sourced/included_by_other_shell_script.sh">
  • ${BASH_SOURCE[1]}是运行它的文件。在这种情况下,它是test_dir="$(get_bash_script_dir)"行的位置,它在同一个文件中
  • ${BASH_SOURCE[2]}是运行的文件。在这种情况下,它是source ...线的位置,它在"/tmp/main/sourcing_test.sh">

"${BASH_SOURCE[-1]}"将获得数组中的最后一个条目,它将是所有调用文件(即主脚本)的父项。如果您知道运行函数的确切上下文,也可以使用例如"${BASH_SOURCE[2]}"来获得所需的特定调用级别。

顺便说一句,将source0添加到函数中会非常清楚地显示这一点。

最新更新