如何从源代码中的源代码函数返回?

时间:2012-02-15 14:23:32

标签: bash function include

考虑foo.sh:

#!/bin/bash
function foo() {
   source another.sh
   echo "This shouldn't be executed. Return code: $?"
   return 0
}

foo
echo "Return code: $?"

然后是另一个.sh:

echo "Inside another.sh"
return 1

运行./foo.sh打印:

Inside another.sh
This shouldn't be executed. Return code: 1
Return code: 0

是否有另一种方法将源文件包含到另一个中,以便return命令从函数封闭包含命令而不是从命令本身返回?

1 个答案:

答案 0 :(得分:1)

一个选项是在foo.sh中传播返回代码

source another.sh || return $?

然后:

$ ./foo.sh
Inside another.sh
Return code: 1

或者,退出另一个.sh:

中的整个脚本
exit 1

然后:

$ ./foo.sh
Inside another.sh
$ echo $?
1