2012-09-04 38 views
3

下面是bash腳本退出並不在bash

#!/bin/bash 
set -x 
function doSomething() { 
    callee 
    echo "It should not go to here!" 
} 

function callee() { 
    (echo "before") && (echo "This is callee" && exit 1)                     
    echo "why I can see this?" 
} 


doSomething 

,這是結果...

+ set -x 
+ doSomething 
+ callee 
+ echo before 
before 
+ echo 'This is callee' 
This is callee 
+ exit 1 
+ echo 'why I can see this?' 
why I can see this? 
+ echo 'It should not go to here!' 
It should not go to here! 

我看到命令「退出」,但它並沒有退出工作退出腳本

爲什麼退出不起作用?

回答

5

您從子shell中調用exit,所以這是退出的shell。試試這個:

function callee() { 
    (echo "before") && { echo "This is callee" && exit 1; }                     
    echo "why I can see this?" 
} 

然而,這將從任何叫做callee的殼中退出。您可能想使用return而不是exit從該功能返回。

3

當您在()中運行命令時,您正在生成一個子shell。因此,當您在該子外殼中調用exit時,您只是退出它,而不是您的頂級腳本。

0

因爲全局假設創建了一個新的嵌套shell,它以exit退出。