我有一棵这样的树:
repo
|-- dir
| |-- main_script.sh
| |-- subdir
| | |-- scritp1.sh
| | |-- script2.sh
我想在script1.sh中输入script2.sh,在main_script.sh中输入source1.sh,然后从repo调用main_script:
$ pwd
.../repo
$ bash ./dir/main_script.sh
问题在于以下脚本:
main_script.sh:
#!/usr/bin/env bash
source ./subdir/script1.sh
script1.sh:
#!/usr/bin/env bash
source script2.sh
script2.sh:
#!/usr/bin/env bash
echo "Something useful"
我收到错误./dir/main_script.sh: line 2: ./subdir/script1.sh: No such file or directory
。似乎bash正在寻找不与main_script.sh相关但与工作目录相关的子目录。我可以使用接受的答案表单this question或this blog post更改第一个脚本以获取脚本的位置,使main_script.sh看起来像这样:
#!/usr/bin/env bash
MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "${MYDIR}/subdir/script1.sh"
但是我在script1.sh中获取script2.sh时遇到错误:
...repo/dir/subdir/script1.sh: line 2: script2.sh: No such file or directory
因为bash似乎在工作目录中寻找script2.sh。
我不想在每个脚本中嵌入目录结构。 那么,问题是如何正确地在bash中导入相关脚本?
答案 0 :(得分:1)
PATH受source
命令的尊重。因此,您只能在一个地方编辑它,新的PATH将由所有其他人继承:
mydir=${BASH_SOURCE#/*} # the normalization being done previously was needless
# (and all-caps names are reserved for variables with
# meaning to the shell or operating system).
PATH="$mydir:$mydir/subdir:$PATH" # no export needed for a variable already in environment
source script1.sh # use non-qualified path