我有一个
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