尝试运行一个bash脚本,该脚本的源代码来自作为源代码运行的另一个脚本

时间:2022-03-20 01:48:00

I have a bash script that will eventually call another bash script. Each script must be run with "source". For simplicity's sake, I've summarized the problem points below

我有一个bash脚本,它最终将调用另一个bash脚本。每个脚本必须使用“源”运行。为了简单起见,我总结了下面的问题点

script1.sh:

script1.sh:

source script2.sh

script2.sh:

script2.sh:

export someVar=something

Run everything with:

运行的一切:

source script1.sh arg1 arg2

The issue is when script2.sh is run from script1.sh, the arguments are also copied, so script2.sh is actually run as:

问题是script2。sh是从script1运行的。参数也被复制,所以script2。sh实际上运行为:

source script2.sh arg1 arg2

script2.sh fails because those arguments are provided. Is there any way that I can run script2 from script1 without passing those args? Running script2 without the source command is not an option, unless there is another way for it to be run and let the variables persist. I also can not modify script2 in any way.

script2。sh失败是因为提供了这些参数。有什么方法可以在script1上运行script2而不传递这些args?不使用源命令运行script2不是一个选项,除非有另一种方法可以运行它并让变量保持不变。我也不能以任何方式修改script2。

1 个解决方案

#1


2  

You can clear the positional parameters using set -- when you're done with them:

您可以使用set清除位置参数——当您完成它们时:

script1.sh:

script1.sh:

echo "Number of parameters before: $#"
set --
echo "Number of parameters after : $#"
source script2.sh

script2.sh:

script2.sh:

echo "script2.sh received $# parameters"

Now script1.sh foo bar will print

现在script1。sh foo bar会打印

Number of parameters before: 2
Number of parameters after : 0
script2.sh received 0 parameters

#1


2  

You can clear the positional parameters using set -- when you're done with them:

您可以使用set清除位置参数——当您完成它们时:

script1.sh:

script1.sh:

echo "Number of parameters before: $#"
set --
echo "Number of parameters after : $#"
source script2.sh

script2.sh:

script2.sh:

echo "script2.sh received $# parameters"

Now script1.sh foo bar will print

现在script1。sh foo bar会打印

Number of parameters before: 2
Number of parameters after : 0
script2.sh received 0 parameters