首页 > 解决方案 > 如何从使用 while 循环的函数返回

问题描述

在我的脚本的主体中,我有以下内容:

while   read -p "Enter operand: " first
        checkRecall
...

其中checkRecall定义为:

checkRecall() {
    if [ "$next" = MR -a "$times" -ne 0 ]; then
        next=$MS
        echo "M -> $MS"
    elif [ "$first" = MR -a "$times" -eq 0 ]; then
        while   [ "$first" = MR ] # <-- PROBLEM: exits script when no longer true
        do
            echo "Nothing in memory"
            read -p "Enter a different operand: " first
        done
    fi
}

times是在脚本主体中递增的变量。

[ "$first" = MR -a "$times" -eq 0 ]当条件不再为真时,我试图将控制流返回到脚本的主体。相反,它退出了我的脚本。我如何实现这一目标?

而不是while [ "$first" = MR -a "$times" -eq 0 ],我尝试使用以下if/else语句return

 while    if [ "$first" != MR ]; then
              return 1
          fi
          [ "$first" = MR ]

但这似乎不起作用。

标签: bash

解决方案


我已经完成了主脚本的其余部分,没有看到任何会导致它过早退出的内容。很可能我错过了一些东西,或者我在某个地方有误解,但 FWIW 我现在能够想出一个解决方案:

while   [ "$first" = MR ]
        do
            echo "Nothing in memory"
            read -p "Enter a different operand: " first
            if [ $first != MR ]; then return
            fi
        done

推荐阅读