簡體   English   中英

如何添加命令以將任何值放在參數上以回顯無效輸入

[英]how can i add a command to put any value on an argument to echo invalid input

我必須保留“是”和“否”的選擇,但我想輸入一些內容,如果我不輸入“是”或“否”以表明這是不可能的,我對此並不陌生,不知道該怎么做

echo "Do you wish to Exit?(yes/no)"
read input
if [ "$input" == "yes" ]
then
clear
exit
elif [ "$input" == "no" ]
then 
clear 
echo "Reloaded"
echo -e "\n"
elif [ "$input" == * ]
then
echo "Invalid Input"
fi ;;

您在這里走在正確的軌道上,但是最后的條件檢查會導致問題。

您正在檢查最后一個塊中的"$input" == *是否。 當你像這樣單獨使用*時,你會得到一些古怪的行為。 shell 嘗試將其展開到當前目錄中的所有文件。 這意味着您可能會為條件提供太多 arguments,並且當當前目錄中有多個文件時,應該會收到類似於[: too many argument的錯誤。 如果目錄為空,除了給定的腳本,條件將擴展為elif [ "$input" == some_file.txt]並且腳本將繼續並正常退出而沒有所需的 output。 請參閱 bash 模式匹配命令擴展文檔。

這里最簡單的解決方案是使用else代替。 如果前兩個條件不滿足,則此塊將執行,因此$inputs不是是或否。 請參閱bash 條件文檔。 您的腳本應如下所示:

echo "Do you wish to Exit?(yes/no)"
read input

if [ "$input" == "yes" ]
then
  clear
  exit
elif [ "$input" == "no" ]
then
  clear
  echo "Reloaded"
  echo -e "\n"
else
  echo "Invalid Input"
fi

作為最后的評論,您可以通過利用-p參數將read命令簡化為 1 行,來自用法:

-p prompt output the string PROMPT without a trailing newline before attempting to read

所以你可以將你的閱讀濃縮成read -p 'Do you wish to Exit? (yes/no)' input read -p 'Do you wish to Exit? (yes/no)' input

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM