为什么我的while循环不起作用?我正在尝试写一个bash脚本,只要我没有选择第四个循环

为什么我的while循环不起作用?我正在尝试写一个bash脚本,只要我没有选择第四个循环,bash,if-statement,while-loop,Bash,If Statement,While Loop,这是我的密码 每次我按1,2或3,所以我退出了它的执行,但退出我得到了!永久循环 我做错了什么 echo "Wrhat is your name ! :" read Name echo "Hello $Name ! What would you like me to do ?" echo "Press 1 to create a note !" echo "Press 2 to write a text and save it in a note?" echo "Press 3 to copy

这是我的密码 每次我按1,2或3,所以我退出了它的执行,但退出我得到了!永久循环 我做错了什么

echo "Wrhat is your name ! :"
read Name
echo  "Hello $Name ! What would you like me to do ?"
echo "Press 1 to create a note !"
echo "Press 2 to write a text and save it in a note?"
echo "Press 3 to copy your new note ?"
echo "Press 4 to exit ?"
echo $Name >> Note.txt 
read Num
while [[ "$Num" != "4" ]] ; do
    if  [[ $Num = "1" ]]; then
        echo > Note.txt
        echo "Done!"
    elif [[ $Num = "2" ]]; then
        echo "Write your text : "
        read text
        echo $text >> Note.txt
        echo "Done!"
    elif [[ $Num = "3" ]]; then
        cp Note.txt Note1.txt
    else
        exit 0
    fi
done
您需要在每次迭代的循环结束时更新(读取)$Num变量

echo "Wrhat is your name ! :"
read Name
echo  "Hello $Name ! What would you like me to do ?"
echo "Preas 1 to create a note !"
echo "Preas 2 to write a text and save it in a note?"
echo "Preas 3 to copy your new note ?"
echo "Preas 4 to exit ?"
echo $Name >> Note.txt 
read Num
while [[ "$Num" != "" ]] ; do
    if  [[ $Num = "1" ]]; then
        echo > Note.txt
        echo "Done!"
    elif [[ $Num = "2" ]]; then
        echo "Write your text : "
        read text
        echo $text >> Note.txt
        echo "Done!"
    elif [[ $Num = "3" ]]; then
        cp Note.txt Note1.txt
    else
        exit 0
    fi
    read Num
done

有一些变化的替代方案:

  • 谢邦补充道

  • 修正了“你叫什么名字”的输入错误

  • 报价为“$Name”

  • 集成“while”中的“read Num”

  • “case”而不是“if…elif…”

  • 关于不需要的输入的错误消息

代码如下:

#!/bin/bash

echo "What is your name ! :"
read Name
echo  "Hello $Name ! What would you like me to do ?"
echo "Press 1 to create a note !"
echo "Press 2 to write a text and save it in a note?"
echo "Press 3 to copy your new note ?"
echo "Press 4 to exit ?"
echo "$Name" >> Note.txt 

while read Num; do
    case "$Num" in

     1) echo > Note.txt
        echo "Done!"
        ;;

     2) echo "Write your text : "
        read text
        echo $text >> Note.txt
        echo "Done!"
        ;;

     3) cp Note.txt Note1.txt
        ;;

     4) break 2
        ;;

     *) echo "Input error"
        ;;
    esac
done

Num
从不在循环内部更改,那么为什么您认为循环应该停止?应该如何让它停止?您不需要
内部
[[…]]
。移动
读取Num
内部
而[[“$Num”!=“4”];do
@KhaledMustafa不要忘记这些答案中是否有一个解决了您的问题。或者,最好初始化变量,然后在循环开始处读取。