微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐