简体   繁体   中英

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

i have to keep the yes and no choice but i want to put something that if i don't type yes or no to show that this is not possible i am new to this and not sure what to do

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 ;;

You are on the right track here, the last condition check is causing issues however.

You are checking if "$input" == * in the last block. When you use * on its own like that you can get some wacky behavior. The shell tries to expand it to all the files in the current directory. This means that you will likely be giving too many arguments to the conditional and should get an error similar to [: too many argument when there are several files in the current directory. If the directory is empty except for the given script the conditional will be expanded to elif [ "$input" == some_file.txt] and the script will continue and exit normally without the desired output. See the bash pattern matching and command expansion documentation.

The simplest solution here is to use an else instead. This block will execute if the first two conditions are not met, and therfore $inputs is something other than yes or no. See the bash conditional documentation. You script should look something like this:

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

As a final comment, you can simplify the read command into 1 line by leveraging the -p argument, from the usage:

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

So you can condense your read into read -p 'Do you wish to Exit? (yes/no)' input read -p 'Do you wish to Exit? (yes/no)' input

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM