【问题标题】:How to Properly Set Up If in While Loop如果在 While 循环中如何正确设置
【发布时间】:2021-06-23 14:58:25
【问题描述】:

稍后我将把其余的功能添加到程序中,它仍处于早期阶段,但由于某种原因,我似乎无法退出 while 循环,即使 if 语句在其中并且在菜单。这是到目前为止的代码。

continue="true"

#while loop to keep the code running till the user inputs Q
while [ $continue = "true" ] 

#loop start
do
        #clearing screen before showing the menu
        clear
        echo "A to Create a user account"
        echo "B to Delete a user account"
        echo "C to Change Supplementary Group for a user account"
        echo "D to Create a user account"
        echo "E to Delete a user account"
        echo "F to Change Supplementary Group for a user account"
        echo "Q to Quit"
        read -p "What would you like to do?:" choice

        #Test to end the program
        if [ $choice = 'Q' ] || [ $choice = 'q']
                then
                $continue="false"
        fi
#loop end
done```

【问题讨论】:

  • break 是您正在寻找的。 help break 了解更多信息。此外,您不需要[ ] 或任何测试,如果无限循环是您所追求的,这里while true; do...; donewhile :; do ....; donehelp :
  • 对于我的分配,我不允许使用 exit 或 break 语句退出 while 循环
  • 太棒了!那玩得开心。
  • $continue=false 是语法错误。您不能在作业的左侧使用$。放一个shebang并将您的代码粘贴到shellcheck.net
  • 使用$获取变量的值,而不是设置它。

标签: linux bash if-statement while-loop scripting


【解决方案1】:

作为pointed out by Gordon,您需要continue="false" 而不是$continue="false"

另外,我建议使用if [ "$choice" = 'Q' ] || [ "$choice" = 'q' ],这样如果用户点击 CR 并且没有输入任何内容,您的脚本就不会中断。 (另请注意,该语句中最后一个 ] 之前需要一个空格。)

【讨论】:

    【解决方案2】:

    虽然语法错误已在 cmets 中突出显示,但我建议完全避免使用 continue 变量,使用 break。您还可以使用正则表达式组合这两项检查。像这样的

    while true; do
        read -p "What would you like to do?: " choice
        if [[ "$choice" =~ [Q|q] ]]; then
            break
        fi
    done
    

    虽然当我查看您问题中的 echo 语句时,您似乎最好完全避免使用 if 语句,而是使用 case 语句

    while true; do 
        read -p "What would you like to do?: " choice
        case "$choice" in
            q|Q) break 
                ;; 
            a|A) echo "Creating a user account"
                ;;
            #This catches anything else
            *) echo "unknown option"
                ;; 
        esac 
    done
    

    【讨论】:

      猜你喜欢
      • 2019-03-01
      • 2017-10-05
      • 2020-11-23
      • 1970-01-01
      • 2021-10-19
      • 2013-05-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多