Bash 在执行另一个脚本之前,有没有一种好方法可以预加载或包含脚本?

Bash 在执行另一个脚本之前,有没有一种好方法可以预加载或包含脚本?,bash,Bash,我希望执行一个脚本,但在它执行之前要包含另一个脚本。问题是,将生成包含的脚本,而执行的脚本将不可修改。我提出的一个解决方案是,通过将include脚本作为包装器,调用set来设置已执行脚本的参数,然后对其进行点处理/寻源,从而实际反转include。例如 #!/bin/bash # Generated wrapper or include script. : Performing some setup... target_script=$1 ; shift set -- "$@" . "$ta

我希望执行一个脚本,但在它执行之前要包含另一个脚本。问题是,将生成包含的脚本,而执行的脚本将不可修改。我提出的一个解决方案是,通过将include脚本作为包装器,调用
set
来设置已执行脚本的参数,然后对其进行点处理/寻源,从而实际反转include。例如

#!/bin/bash
# Generated wrapper or include script.
: Performing some setup...

target_script=$1 ; shift
set -- "$@"
. "$target_script"
其中
target\u script
是我实际想要运行的脚本,从包装器导入设置

但是,我面临的潜在问题是,目标脚本的调用者,甚至目标脚本本身,可能希望将
$0
设置为它在文件系统上的位置路径。但是由于这种包装方法覆盖了
$0
,因此
$0
的值可能是意外的,并且可能会产生未定义的行为

是否有另一种方法可以通过bash在不干扰其运行时参数的情况下,以脚本形式执行有效的
LD_预加载


我已经查看了
--init file
--rcfile
,但这些似乎只包括在交互式shell中。

强制交互式模式似乎允许我指定
--rcfile

$ bash --rcfile /tmp/x-include.sh -i /tmp/xx.sh
include_script: $0=bash, $BASH_SOURCE=/tmp/x-include.sh
target_script: $0=/tmp/xx.sh, $BASH_SOURCE=/tmp/xx.sh
x-include.sh
脚本的内容:

#!/bin/bash
echo "include_script: \$0=$0, \$BASH_SOURCE=$BASH_SOURCE"
#!/bin/bash
echo "target_script: \$0=$0, \$BASH_SOURCE=$BASH_SOURCE"
xx.sh
脚本的内容:

#!/bin/bash
echo "include_script: \$0=$0, \$BASH_SOURCE=$BASH_SOURCE"
#!/bin/bash
echo "target_script: \$0=$0, \$BASH_SOURCE=$BASH_SOURCE"

从bash文档中:

When bash is started non-interactively, to run a shell script, for example, it looks for the variable  BASH_ENV  in
the  environment,  expands its value if it appears there, and uses the expanded value as the name of a file to read
and execute.  Bash behaves as if the following command were executed:
       if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi
but the value of the PATH variable is not used to search for the file name.
那么就这样解决了:

BASH_ENV=/tmp/x-include.sh /bin/bash /tmp/xx.sh

嗯……我想我有一个更好的主意(这就是为什么我删除了关于
bash-I--init file
)的注释),但效果不是很好;
BASH.*
变量的结果很奇怪
bash-i--init文件
可能是侵入性最小的文件;我不知道有多少脚本可以检查它们运行的shell是否是交互式的。我也尝试过,它没有产生任何太不利的结果。见下面我的答案。如果你想回答,我会删除我自己的答案,因为它是受你的建议启发的…不,没关系。没有必要为互联网问题争吵。