函数while循环中的返回如何处理? [英] How is return handled in a function while loop?

查看:57
本文介绍了函数while循环中的返回如何处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,并且在该函数内部是一个while循环.

I have a function, and inside that function is a while loop.

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

When I try to set a non local variable inside the while loop with an IF statement, then exit the entire function, suddenly the variable is no longer set?

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从函数中传递出去.是返回"导致脚本中断循环,而不是函数中断?

For some reason, RETURN is empty. I have done this many many many times in the past though. Something about the while loop is preventing RETURN from being passed out of the function. Is "return" causing the script to break the loop and not the function?

谢谢

推荐答案

最简单的解决方案是首先使用输入重定向而不是管道来避免使用子外壳.

The easiest solution is to avoid the subshell in the first place, by using input redirection instead of a pipeline.

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中运行,而不是一个子壳.这样,分配给 RETURN 的值将在管道完成后保留.

In cases where the pipeline is unavoidable, bash 4.2 introduced the lastpipe option, which when enabled allows the last command in a pipeline to run in the current shell, not a subshell. This way, the value assigned to RETURN would be retained after the pipeline completes.

更好的是,使用标准机制来发信号通知错误.无需设置自定义参数的值,只需返回一个非零值即可:

Even better, use the standard mechanism for signaling an error. Instead of setting the value of a custom parameter, just return a non-zero value:

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
}

这篇关于函数while循环中的返回如何处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆