bash – 源函数中的文件采用函数参数

我有一个 shell脚本,它在一个函数的上下文中获取第二个参数:

#!/bin/bash
# bar.sh

function f()
{
   source foo.sh
   echo "Do something else with $1,after foo.sh is sourced."
}

f bar

和:

#!/bin/bash
# foo.sh

x=${1:-"default"}
echo $x

执行输出如下:

$./bar.sh 
bar
Do something else with bar,after foo.sh is sourced.

我原本希望认为第一行输出而不是bar.事实证明,即使我没有将任何参数传递给foo.sh,它也会从函数f的上下文中获取1美元.我可以通过阅读bash documentation了解这种行为,但是覆盖它的最佳方法是什么?

解决方法

编辑:根据您的评论和编辑问题:

#!/bin/bash
# bar.sh

function f()
{
   # save $1
   arg1="$1"
   # unset $1
   shift
   # source your script; prints default
   source ./foo.sh
   # restore $1
   set -- $arg1
   # should print bar
   echo $1
   echo "Do something else with $1,after foo.sh is sourced."
}

f bar

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...