扩展 redneb 的(当前接受的)答案...
TL;DR需要在另一个脚本中获取没有位置参数的脚本?试试function DoSource() { source test.sh ; } ; DoSource 而不是source test.sh。
sourceing 在另一个脚本中没有参数的脚本
问题中 Bash 手册的摘录显示了如何将位置参数分配给源脚本的详细信息。特别是,如果源命令没有指定任何参数,它会被分配来自调用环境的参数。
结果是source 一个脚本不传递参数 在另一个脚本中可能很麻烦。
例如,让我们使用 redneb 示例为test.sh:
echo "I was given $# argument(s):"
printf "%s\n" "$@"
来源于另一个脚本userScript.sh,例如单线:
source test.sh
运行上述示例时:
$ bash userScript.sh a 'b c'
I was given 2 argument(s):
a
b c
test.sh 继承 userScript.sh 位置参数...现在不是我想要的(如果我这样做了,我可以使用 source test.sh "$@")。
我发现以下是一个有用的解决方法:将源命令封装到 Bash 函数中。新的userScript.sh 看起来像:
function DoSource() { source test.sh ; }
DoSource
报告:
$ bash userScript.sh a 'b c'
I was given 0 argument(s):
请注意,指定空参数 (source test.sh '') 并不等效,因为空参数将传递给 test.sh。
如果采购脚本也需要采购
如果userScript.sh 本身应该被采购,那么人们可能不想离开DoSource()。在这种情况下,简单的解决方案是自我毁灭:
function _userScript_sh_DoSource() { source test.sh ; unset "$FUNCNAME" ; }
_userScript_sh_DoSource
一次性使用(已选择函数名称以减少名称冲突的机会);或者unset _userScript_sh_DoSource 命令可以放在不再需要_userScript_sh_DoSource 之后。
多种用途的灵活变体
DoSource() 的更复杂变体:
function DoSource() { local ScriptName="$1" ; shift ; source "$ScriptName" ; }
DoSource test1.sh
DoSource test1.sh "$@"
DoSource test2.sh
可以用作source 的“插入式”替代品,唯一的区别是当没有为要获取的脚本指定位置参数时,source 继承它们,而DoSource 不使用.
但请注意,DoSource 是一个函数,因此在其他方面(例如堆栈调用、FUNCNAME、...)的行为与 source 不同。