2012-02-15 48 views
1

考虑foo.sh:如何从采购源代码中返回源代码?

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

foo 
echo "Return code: $?" 

然后another.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

一种选择是传播返回代码在foo.sh:

source another.sh || return $? 

然后:

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

另外,从整个脚本在another.sh 退出:

exit 1 

然后:

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

刚刚来到相同的解决方案独立。然而,如果'another.sh'将返回0,那么这将不起作用。:) – 2012-02-15 14:40:56

+0

退出此脚本不会执行任何操作,因为我需要在调用foo后继续运行脚本。这只是一个小例子。 – 2012-02-15 14:46:57

+0

@SergiyByelozyorov:你可能想发布*你想要做什么,而不是*如何*。像这样的解决方案(不是很优雅)可以通过采取不同的方法来避免。 – l0b0 2012-02-15 14:51:58