从退出或设置变量的函数退出shell脚本

时间:2013-06-25 12:21:02

标签: linux function shell solaris exit

我有这个问题在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

你怎么解释这个?在我看来,函数是在一个分叉的进程中执行的,它自己终止了它而不是调用者

  1. 有原生方式来执行吗?
  2. 除了通过引用传递参数之外还有其他方法可以执行此操作,如此处所述:Bash - Passing arguments by reference
  3. 提前致谢! 参见Yaniv

0 个答案:

没有答案