[英]Bash does not stop for second `case` statement
在下面的腳本中,如果我在整個腳本中給出y
。 在第二種case $yn in
的情況下,它不會要求 y/n。 它只要求 y/n 一次而不是兩次。
#!/bin/bash
echo -e "\nFirst Step?"
while true; do
case $yn in
[Yy]* ) echo "going through first"; break;;
[Nn]* ) exit;;
* ) read -p "Please answer yes or no: " yn;;
esac
done
echo -e "\nSecond Step?"
while true; do
case $yn in
[Yy]* ) echo "going through second"; break;;
[Nn]* ) exit;;
* ) read -p "Please answer yes or no: " yn;;
esac
done
如何解決這個問題呢。
在每個循環中將read
命令移到 case 語句的上方。
shopt -s nocasematch
printf '\nFirst step\n'
while true; do
read -p "Please answer yes or no: " yn
case $yn in
y* ) echo "going through first"; break;;
n* ) exit;;
esac
done
printf '\nSecond step\n'
while true; do
read -p "Please answer yes or no: " yn
case $yn in
y* ) echo "going through second"; break;;
n* ) exit;;
esac
done
或者,使用select
:它為您處理循環,並將變量設置為已知值
PS3="Please answer Yes or No: "
select ans in Yes No; do
case $ans in
Yes) echo "going through nth"; break ;;
No) exit
esac
done
冒着明顯的危險: yn
已經從第一個案例步驟中設置,因此第二次不需要將 go 設置為默認案例並再次讀取輸入。
只需將第二個yn
重命名為yn2
或類似名稱。
#!/bin/bash
echo -e "\nFirst Step?"
while true; do
case $yn in
[Yy]* ) echo "going through first"; break;;
[Nn]* ) exit;;
* ) read -p "Please answer yes or no: " yn;;
esac
done
echo -e "\nSecond Step?"
while true; do
case $yn2 in
[Yy]* ) echo "going through second"; break;;
[Nn]* ) exit;;
* ) read -p "Please answer yes or no: " yn2;;
esac
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.