1

I am trying to have a script give me the output of multiple words and variations of the words. I tried putting in the -o for the variable, quoting the words, piping them together. The words for each varname are the indicated words that I want to have output to me. Is there a way to correct this, or does each variable need to be set individually? Such as varname1=even varname2=Even varname3=EVEN, etc.

#!/bin/bash

varname1=even -o Even -o EVEN
varrname2=odd -o Odd -o ODD
varname3=zero -o Zero -o ZERO
varname4=negative -o Negative -o NEGATIVE

# Ask the user for one of four select words
echo "Type one of the following words:"
echo "even, odd, zero, negative"
read varword
if [[ ("$varword" = $varname1 ) || ("$varword" = $varname2 ) || ("$varword" = $varname3 ) || ("$varword" = $varname4 ) ]]
then
    echo "The approved word you have selected is $varword, great work! "
else
    echo "The unapproved word you have selected is $varword, Please try again."
fi
  • 2
    What are you really trying to do? Why not just always downcase the input and stop the upperCase-lowerCase permutation madness? – PSkocik Nov 29 '15 at 0:15
1
echo "Type one of the following words:"
echo "even, odd, zero, negative"
while :; do
  read varword
  varword="${varword,,}" #downcase it
  case "$varword" in
    even|odd|zero|negative)
      echo "The approved word you have selected is $varword, great work! "; break;;
    *)
      echo "The unapproved word you have selected is $varword, Please try again.";;
  esac
done
0

A way to store several values in one variable would be an array. Here is a documentation on how to use array variables in bash.

However, it seems to me that what you want is case insensitive matching. This can be achieved with grep -iq. i tells grep to match case insensitive and q tells grep that it should only return true or false. Also, you can use the or operator \| in the grep clause to match multiple words. Finally you use the herestring notation <<< to feed the variable directly to grep. This simplifies your script considerably:

#!/bin/bash

# Ask the user for one of four select words
echo "Type one of the following words:"
echo "even, odd, zero, negative"
read varword
if grep -iq "even\|odd\|zero\|negative" <<< "$varword"
then
    echo "The approved word you have selected is $varword, great work! "
else
    echo "The unapproved word you have selected is $varword, Please try again."
fi

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.