2014-12-07 46 views
0

我目前創建了一個unix bash,要求輸入Y/N,然後爲用戶輸入y或n時創建了代碼。但是如果用戶鍵入其他的東西,它會出現「請輸入Y或N」的回聲,那麼我如何重定向它以便返回到原始的Y/N輸入?Unix - 針對Y/N回答問題

#! /bin/bash 

    echo "Do you want to change the directory? Y/N?" 
    read answer 
    if [[ $answer == "y" || $answer == "Y" ]]; then 
    echo "Yes" 
    elif [[ $answer == "n" || $answer == "N" ]]; then 
    echo "No" 
    else 
    echo "Please enter Y or N" 
    #redirect back to "Do you want to change the directory" echo 
    fi 
+1

哪裏是你當前的代碼? – 2014-12-07 13:04:33

+0

剛剛添加的代碼 – james111 2014-12-07 13:10:51

回答

1

這裏有一個解決方案:

#!/bin/bash 

to_do=true 

while $to_do; 
do 
    read -p "Do you want to change the directory? Y/N " answer 
    case $answer in 
     [Yy]*) 
      echo Yes 
      to_do=false 
      ;; 
     [Nn]*) 
      echo No 
      to_do=false 
      ;; 
     *) 
      echo Please enter Y or N 
    esac 
done 
+0

你可以使用'read -p'你想改變目錄嗎? Y/N'答案' – 2014-12-07 13:20:03

+0

我不完全理解編輯?爲什麼需要報價? – 2014-12-07 13:20:05

+0

就像我想要的那樣工作。謝謝 – james111 2014-12-07 13:21:00