我有2个脚本,one.sh和two.sh
one.sh触发对two.sh的调用,内部源/运行其他脚本。我想使用在two.sh中导出的变量来粘贴并在one.sh
中使用它们one.sh:
#!/bin/bash
. ./path/two.sh
echo "VAR: $VAR"
--------------
two.sh
#!/bin/bash
#source/run other .sh scripts
. $(dirname "$0")/../three.sh
export VAR="hello"
当我运行one.sh时,它允许我使用var“VAR”,但是对于内部源或在two.sh中运行的脚本会抛出错误:
./ path / two.sh:line 3:./../three.sh:没有这样的文件或目录
如果我将one.sh更改为以下内容:
one.sh
#!/bin/bash
./path/two.sh --> removed the "." in front of ./path/two.sh
echo "VAR: $VAR"
output: ./one.sh
VAR: ===> NOT EXPORTED
是否有一种方法可以让我在two.sh中导出变量并在one.sh中使用它们,并且还允许我在two.sh中触发/获取其他脚本 如果这看起来有点过于基本但我四处寻找类似的问题而没有找到一个
,请道歉答案 0 :(得分:1)
" one.sh"的第一个版本没关系但是在" two.sh"脚本,如果你运行" dirname $ 0",它总是返回"。"。这使得通往" three.sh"可能无效。我建议你改变:
#source/run other .sh scripts
. $(dirname "$0")/../three.sh
为此:
#source/run other .sh scripts
. $(readlink -f $(dirname "$0"))/../three.sh
或由此:
#source/run other .sh scripts
. $(pwd)/../three.sh
在这种情况下,两个答案是正确的,我更喜欢第一个因为如果" two.sh"跑一个" cd"命令它也会起作用。
答案 1 :(得分:1)
问题在于int two.sh
行看起来像:
. $(dirname "$0")/../three.sh
这会尝试相对于当前正在执行的脚本的位置找到three.sh
。但是,仅仅采购脚本并不重要。当one.sh
来源two.sh
时,$0
的值仍然是one.sh
。
我看到两个合理的解决方案:
将one.sh移动到two.sh的目录中。这样,两个.sh中源文件的相对路径仍然有效。
或者:
从two.sh
移除对$(dirname "$0")/
的所有引用。而是提供明确的路径。