【问题标题】:Ubuntu script never ending loopUbuntu脚本永无止境的循环
【发布时间】:2018-11-14 00:02:01
【问题描述】:

我刚刚开始为大学编写脚本,我正在尝试制作一个菜单,在选择时运行一些功能。现在我只是想让一个菜单出现,但它陷入了无限循环。我根本不擅长编写脚本,但确实需要为课程学习。

while true
do
    echo "1) option1"
    echo "2) option2"
    echo "3) option3"
done

【问题讨论】:

  • 欢迎来到 SO,在 while 循环中,在条件的位置您提供 true,这意味着条件将始终为 TRUE,因此是无限循环。

标签: bash shell ubuntu scripting


【解决方案1】:

在条件位置的 while 循环中,您提供 true,这意味着条件将始终为 TRUE,因此是无限循环。

while 循环是这样工作的:

while condition
if condition is TRUE--> then go inside loop and do operations as per instructions in it.
if condition is FALSE--> then come out of loop since the given condition is no more.

非常基本的while 循环示例:

while ((i<=3))
do
  echo "Hey there..."
  ((i = i +1 ))
done

输出如下。

Hey there...
Hey there...
Hey there...
Hey there...

【讨论】:

  • 我的讲师添加了让我感到困惑的“while true”,因为它没有任何让我感到困惑的条件。你会建议我用什么作为条件,因为我尝试过的一切都没有奏效?
  • @J.walker,我添加了while循环的基本示例,您也可以搜索SO论坛本身以获取更多示例。
【解决方案2】:

对于 shell 中的菜单,使用 select 语句:

PS3='Select your choice: '
select ans in "option1" "option2" "option3" quit
do
    case $ans in
        option1) do_something ;;
        option2) do_something ;;
        option3) do_something ;;
        quit) break ;;
    esac
done

【讨论】:

    猜你喜欢
    • 2016-06-04
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-14
    • 1970-01-01
    • 2019-03-03
    相关资源
    最近更新 更多