微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在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
}

原文地址:https://www.jb51.cc/bash/386637.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐