我在 sh 中有这个问题,需要一个函数来退出卡住的整个脚本或回显一个将由调用者设置为变量的值。
我认为下面的例子最好地解释了这个问题:
#!/bin/sh
do_exit(){
if [ "$1" = "1" ] ; then
echo "name"
return 0
fi
exit 1
}
echo "# That of course should pass"
echo before
var=$(do_exit 1)
echo $var
echo after
echo ""
echo "# Here I expect the func to terminate the script"
echo before
var=$(do_exit 2)
echo $var
echo after
echo ""
echo "# Here I also expect the func to terminate the script"
echo before
var=`do_exit 2`
echo $var
echo after
echo ""
echo "# And this is the only case it exit"
echo before
do_exit 2
echo after
上面的输出是:
# That of course should pass
before
name
after
# Here I expect the func to terminate the script
before
after
# Here I also expect the func to terminate the script
before
after
# And this is the only case it exit
before
你怎么解释?在我看来,该函数是在一个分叉的进程中执行的,该进程自行终止而不是调用者
- 有没有本地的方式来执行它?
- 除了通过引用传递参数之外还有其他方法可以做到这一点:Bash - 通过引用传递参数?
提前致谢!亚尼夫