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.
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
~$ 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
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