Validate if string part of a list

I have this requirement of validating input from user to be one of a list of strings. I validate it as below.

case $1 in
Jan)
     ;;
Feb)
     ;;
.
.
.
Dec)
      ;;
*)
   echo "Invalid input. Should be one of the following."
   echo "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
   ;;
esac

This works fine, but I wanted to know better ways to do this. This code looks lengthy and I'm sure there are more efficient ways to achieve this.

echo $1 |egrep '^(Jan|Feb|Mar|Apr|may|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$' || echo "Invalid Month entered";
1 Like

If your shell is halfway current, this should work without calling external commands:

if [[ $1 != @(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ]]
then
   echo "Invalid input. Should be one of the following."
   echo "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
fi
1 Like

Thanks. I was thinking of egrep but was not getting it spot on.

You could do a little trick, something like:

~$ months=( Jan Feb Mar Apr May Jun )
~$ input=Feb
~$ for i in ${months[@]}; do echo $i; done | grep -c $input
1
~$ input=other
~$ for i in ${months[@]}; do echo $i; done | grep -c $input
0

With awk

echo $1 | awk '/^(Jan|Feb|Mar|Apr|may|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/ {print "Invalid Month entered"}'

or

awk '/^(Jan|Feb|Mar|Apr|may|Jun|Jul|Aug|Sep|Oct|Nov|Dec)$/ {print "Invalid Month entered"}' <<< $1
Months="Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec"
m=Jun
[ "$Months" != "${Months/$m}" ] && echo in || echo out
in
m=Jux
[ "$Months" != "${Months/$m}" ] && echo in || echo out
out

No perfect :slight_smile:

m="Jun Jul"
[ "$Months" != "${Months/$m}" ] && echo in || echo out
in

Why "No perfect"? That string is "in"!
But, well, try this:

[ "$Months" != "${Months/${m/\ }}" ] && echo in || echo out