如何在应用程序的目录树中使源位置独立? [英] How can I make source location-independent within my application's directory tree?

查看:39
本文介绍了如何在应用程序的目录树中使源位置独立?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一棵这样的树:

repo
|-- dir
|   |-- main_script.sh
|   |-- subdir
|   |   |-- scritp1.sh
|   |   |-- script2.sh

我想在 script1.sh 中获取 script2.sh,在 main_script.sh 中获取 script1.sh,然后从 repo 中调用 main_script:

I'd like to source script2.sh in script1.sh and source script1.sh in main_script.sh, then call main_script from repo:

$ pwd
.../repo
$ bash ./dir/main_script.sh

问题在于以下脚本:

main_script.sh:

main_script.sh:

#!/usr/bin/env bash
source ./subdir/script1.sh

script1.sh:

script1.sh:

#!/usr/bin/env bash
source script2.sh

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 无关但与工作目录相关的子目录.我可以更改第一个脚本以使用接受的答案表单获取脚本的位置 这个问题这篇博文 使 main_script.sh 看起来像这样:

I get error ./dir/main_script.sh: line 2: ./subdir/script1.sh: No such file or directory. It seems that bash is looking for subdir not relative to main_script.sh but relative to working dir. I can change first script to get script's location using accepted answer form this question or this blog post making the main_script.sh looking like that:

#!/usr/bin/env bash
MYDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
source "${MYDIR}/subdir/script1.sh"

但是后来我在 script1.sh 中获取 script2.sh 时出错:

But then I get an error on sourcing the script2.sh in script1.sh:

...repo/dir/subdir/script1.sh: line 2: script2.sh: 没有那个文件或目录

似乎 bash 正在工作目录中寻找 script2.sh.

as it seems that bash is looking for script2.sh in working directory.

我不想在每个脚本中嵌入目录结构.那么,问题是如何在bash中正确导入相关脚本?

I don't want to embed directory structure in every script. So, the question is how to import relative scripts in bash properly?

推荐答案

source 命令支持 PATH.因此,您只能在一个地方编辑它,新的 PATH 将被所有其他人继承:

The PATH is honored by the source command. Thus, you can edit it in only one place, and the new PATH will be inherited by all others:

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

这篇关于如何在应用程序的目录树中使源位置独立?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆