bash return在echo"aa"中没有预期的效果 读ln

wen*_*ing 1 bash

#!/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
Run Code Online (Sandbox Code Playgroud)

结果如下

aa
This is callee
It should not go to here!
0
It should go to here!
Run Code Online (Sandbox Code Playgroud)

为什么"回归"就像"休息"一样?

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

cda*_*rke 5

这是因为你使用一个管道进入一个while循环,它在子shell中运行(在Bash中).你是从子shell返回的,而不是函数.试试这个:

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!" 
} 
Run Code Online (Sandbox Code Playgroud)

杀了猫!

  • OP避免UUOC(无用猫)奖的另一个原因. (2认同)