2012-09-13 41 views
1
#!/bin/bash 

function doSomething() { 
    callee 
    echo $? 
    echo "It should go to here!" 
} 

function callee() { 
    cat line.txt |while read ln 
    do 
     echo $ln 
     if [ 1 ] ;then 
      { echo "This is callee" && 
      return 2; } 
     fi 
    done 
    echo "It should not go to here!" 
} 


doSomething 

阅读下面是结果bash return在回声“aa”|中不能正常工作而LN

aa 
This is callee 
It should not go to here! 
0 
It should go to here! 

为什么 “回归” 的工作原理是 “破发”?

我希望它退出该功能!不仅打破循环...

回答

5

这是因为您正在使用管道进入while循环,该循环在子shell(在Bash中)中运行。你从subshel​​l返回,而不是函数。试试这个:

function callee() { 
    while read ln 
    do 
     echo $ln 
     if [ 1 ] ;then 
      echo "This is callee" 
      return 2; 
     fi 
    done < line.txt 
    echo "It should not go to here!" 
} 

杀了猫!

+2

OP的另一个原因是为了避免UUOC(无用猫)奖。 –

+0

该死的好~~~ !!! – wenchiching

1

while在子shell中执行(因为管道),所以你做的任何事情只会在该shell中有效。例如,您不能更改包含范围中变量的值。

+0

所以,这是因为“|” ? – wenchiching

-1

您应该使用

exit [number as status] 

例如

exit 0 

或只是

exit 

exit命令终止脚本。它还可以返回脚本的父进程可用的值。

+0

在这种情况下'exit'仍然只能从子shell中退出,并将控制权返回到运行'while'循环的shell。 – chepner