#!/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
以下是结果
aa
This is callee
It should not go to here!
0
It should go to here!
为什么“返回”的工作方式类似于“休息”?
我希望退出该功能!不仅打破了循环......
答案 0 :(得分: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!"
}
杀死猫!
答案 1 :(得分:1)
while
在子shell中执行(因为管道),所以你所做的任何事情都只会在那个shell中生效。例如,您不能更改包含范围中变量的值。
答案 2 :(得分:-1)
你应该使用
exit [number as status]
例如
exit 0
或只是
exit
exit命令终止脚本。它还可以返回一个值,该值可供脚本的父进程使用。