在bash函数中返回语句的行为
发布时间:2020-12-15 18:52:54 所属栏目:安全 来源:网络整理
导读:我无法理解bash中内置的返回行为.这是一个示例脚本. #!/bin/bashdostuff() { date | while true; do echo returning 0 return 0 echo really-notreached done echo notreached return 3}dostuffecho returncode: $? 该脚本的输出是: returning 0notreachedr
我无法理解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语句打破了循环,subshel??l结束,让你的功能继续下去.
您必须重新构建代码以删除管道,以便不创建子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 } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |