如何在 While 循环中正确设置 If

How to Properly Set Up If in While Loop

我打算稍后将其余功能添加到程序中,它仍处于早期阶段,但由于某种原因我似乎无法退出 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```

作为 ,您需要 continue="false" 而不是 $continue="false"

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

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

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