在bash函数中返回语句的行为

我无法理解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
}

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...