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