在下面的腳本中,如果我給y一次它遍歷整個腳本。在 second 的情況下它不要求 y/n case $yn in。它只要求 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
如何解決這個問題呢。
uj5u.com熱心網友回復:
在每個回圈中將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
uj5u.com熱心網友回復:
冒著危險說明顯的:yn已經從第一個案例步驟設定,所以第二次不需要轉到默認案例并再次讀取輸入。
只需將第二個重命名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
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/378766.html
標籤:猛击
下一篇:在Shell腳本中匹配列和行
