前端之家收集整理的这篇文章主要介绍了
在bash函数中返回语句的行为,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_
403_0@
我无法理解bash中内置的返回行为.这是一个示例脚本.
#!/bin/bash
dostuff() {
date | while true; do
echo returning 0
return 0
echo really-notreached
done
echo notreached
return 3
}
dostuff
echo returncode: $?
该脚本的输出是:
returning 0
notreached
returncode: 3
但是,如果日期|从第4行中删除,输出符合我的预期:
returning 0
returncode: 0
看起来像上面使用的return语句是以我认为break语句行为的方式,但只有当循环位于管道的右侧时才行.为什么会这样?我在bash手册页或在线上找不到任何解释这个行为的东西.脚本在bash 4.1.5和破折号0.5.5中的方式相同.
在日期|而…的情况下,由于存在管道,while循环在子shell中执行.因此,return语句打破了循环,subshell结束,让你的
功能继续下去.
您必须重新构建代码以删除管道,以便不创建子shell:
dostuff() {
# redirect from a process substitution instead of a pipeline
while true; do
echo returning 0
return 0
echo really-notreached
done < <(date)
echo notreached
return 3
}