gpt4 book ai didi

bash - 如何在函数 while 循环中处理 return ?

转载 作者:行者123 更新时间:2023-12-04 02:35:40 24 4
gpt4 key购买 nike

我有一个函数,在该函数内部是一个 while 循环。

当我尝试使用 IF 语句在 while 循环中设置非局部变量,然后退出整个函数时,突然不再设置变量?

function EXAMPLE {
cat test.txt | while read LINE; do
if [ "$LINE" = "FAIL" ]; then
echo "Detected FAIL in file! Setting RETURN=fail and exiting function."
RETURN="fail"
return
fi
done
}

### START SCRIPT ###
EXAMPLE (Call example function)
echo "$RETURN"

出于某种原因,RETURN 为空。不过,我过去已经做过很多次了。关于 while 循环的某些事情阻止了 RETURN 被传递出函数。 “返回”是否导致脚本中断循环而不是函数?

谢谢

最佳答案

最简单的解决方案是首先通过使用输入重定向而不是管道来避免使用 subshel​​l。

function EXAMPLE {
while IFS= read -r line; do
if [ "$line" = "FAIL" ]; then
echo "Detected FAIL in file! Setting RETURN=fail and exiting function."
RETURN="fail"
return
fi
done < test.txt
}

在管道不可避免的情况下, bash 4.2 介绍了 lastpipe选项,启用后允许管道中的最后一个命令在当前 shell 中运行,而不是在子 shell 中运行。这样,赋值给 RETURN管道完成后将保留。

更好的是,使用标准机制来发出错误信号。而不是设置自定义参数的值,只需返回一个非零值:
function EXAMPLE {
while IFS= read -r line; do
if [ "$line" = "FAIL" ]; then
echo "Detected FAIL in file! Exiting function with status 1."
return 1
fi
done < test.txt
}

关于bash - 如何在函数 while 循环中处理 return ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20910112/

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