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

Ato*_*lan 4 bash return while-loop

我有一个函数,该函数内部有一个 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"
Run Code Online (Sandbox Code Playgroud)

由于某种原因,RETURN 为空。不过,我过去已经做过很多很多次了。while 循环的某些问题导致 RETURN 无法从函数中传递出来。“return”是否导致脚本中断循环而不是函数?

谢谢

che*_*ner 5

最简单的解决方案是首先避免使用子 shell,使用输入重定向而不是管道。

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
}
Run Code Online (Sandbox Code Playgroud)

在管道不可避免的情况下,bash4.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
}
Run Code Online (Sandbox Code Playgroud)