加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

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

发布时间:2020-12-15 20:59:42 所属栏目:安全 来源:网络整理
导读:我有一个 shell脚本,它在一个函数的上下文中获取第二个参数: #!/bin/bash# bar.shfunction f(){ source foo.sh echo "Do something else with $1,after foo.sh is sourced."}f bar 和: #!/bin/bash# foo.shx=${1:-"default"}echo $x 执行输出如下: $./bar
我有一个 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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读