gpt4 book ai didi

bash - Bash 函数中 'return' 语句的行为

转载 作者:行者123 更新时间:2023-11-29 08:45:24 26 4
gpt4 key购买 nike

我无法理解 Bash 中内置的 return 的行为。这是一个示例脚本。

#!/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

但是,如果 date | 从第 4 行中删除,输出如我所料:

returning 0
returncode: 0

似乎上面使用的 return 语句的行为方式与我认为 break 语句的行为方式相同,但只有当循环位于右侧时一个管道。为什么会这样?我在 Bash man page 中找不到任何解释此行为的内容。或在线。该脚本在 Bash 4.1.5 和 Dash 中的行为方式相同0.5.5.

最佳答案

日期 | while ... 场景,由于管道的存在,while 循环在子 shell 中执行。因此,return 语句会中断循环,子 shell 结束,让您的函数继续运行。

您必须重构代码以删除管道,这样就不会创建子 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
}

关于bash - Bash 函数中 'return' 语句的行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7109720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com