bash return doesn't work as expect in echo “aa” | while read ln

雨燕双飞 提交于 2021-02-16 14:35:12

问题


#!/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

Below is the result

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

Why "return" works like "break" ?

I want it exit the function! not only break the loop ...


回答1:


This is because you are using a pipe into a while loop, which runs in a subshell (in Bash). You are returning from the subshell, not the function. Try this:

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!" 
} 

Kill the cat!




回答2:


The while executes in a subshell (because of the pipe), so anything you do will only have effect within that shell. You can't, for instance, change values of variables in the containing scope.




回答3:


You should use

exit [number as status]

for example

exit 0

or just

exit

The exit command terminates a script. It can also return a value, which is available to the script's parent process.



来源:https://stackoverflow.com/questions/12407048/bash-return-doesnt-work-as-expect-in-echo-aa-while-read-ln

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!