我有这个问题在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
你怎么解释这个?在我看来,函数是在一个分叉的进程中执行的,它自己终止了它而不是调用者
提前致谢! 参见Yaniv