ksh validating string with logical OR
Solution 1
if ! [[ "$Mode" == "C" || "$Mode" == "M" ]] ; then
echo ""
echo "*Not a valid value*"
exit 2;
fi
I think this is the easier way to test multiple values. I like to think of it 'if Mode is NOT in the list of C, or M, or ....; then ....' I see beginners post code like yours (and I did it myself when I was a beginner), because then your mental model is 'if Mode is NOT C OR Mode is NOT M then ...', but you you really need the 'AND' instead (as illustrated by jlliagre).
I hope this helps.
Solution 2
Your logic is flawed.
if [[ "$Mode" != "C" ]] && [[ "$Mode" != "M" ]]
then
echo ""
echo "*Not a valid value*"
exit 2;
fi
Solution 3
Years later...
For those who may follow, the reason amer's logic is flawed is, $Mode is always either not "C" OR not "M", because even a value like "C" is not "M", which makes the 2nd condition true.
Here are 2 one-liner alternatives:
[[ $Mode != "C" && $Mode != "M" ]] && echo -e "\n*Not a valid value*" && exit 2
This bash alterative allows for easy and concise adding of more valid values:
[[ `echo $Mode | egrep "C|M"` ]] || echo -e "\n*Not a valid value*" && exit 2
Why is everyone writing "$Mode" instead of just $Mode? Try it before you answer, please.
amer
Updated on June 08, 2022Comments
-
amer almost 2 years
I am writing a script in ksh which needs to check a variable is set to one of the two accepted values. I have got the following code but when I enter a valid value e.g. "C" I get the error message (Not a valid value):
if [[ "$Mode" != "C" ]] || [[ "$Mode" != "M" ]] then echo "" echo "*Not a valid value*" exit 2; fi
I am not sure why it is failing on the string comparison, I have tried varations on syntax but still not getting anywhere, any help would be much appreciated.