2012-02-15 77 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