ksh 使用逻辑 OR 验证字符串
我正在 ksh 中编写一个脚本,它需要检查变量是否设置为两个接受值之一。我有以下代码,但是当我输入有效值(例如“C”)时,我收到错误消息(不是有效值):
if [[ "$Mode" != "C" ]] || [[ "$Mode" != "M" ]]
then
echo ""
echo "*Not a valid value*"
exit 2;
fi
我不确定为什么它在字符串比较中失败,我尝试了语法变化,但仍然无处可去,任何帮助将不胜感激。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我认为这是测试多个值的更简单的方法。我喜欢这样想:“如果模式不在 C、M 或 .... 列表中;然后......'我看到初学者发布像你这样的代码(当我还是初学者时我自己这样做),因为那么你的心智模型是“如果模式不是C或模式不是M那么......”,但是你确实需要“AND”(如 jlliagre 所示)。
我希望这有帮助。
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.
你的逻辑有缺陷。
Your logic is flawed.
多年后...
对于那些可能关注的人来说,美国人的逻辑有缺陷的原因是,$Mode 总是要么不是“C”,要么不是“M”,因为即使像“C”这样的值不是“M”,这使得第二个条件成立。
这里有 2 个单行替代方案:
这个 bash 替代方案可以轻松简洁地添加更多有效值:
为什么每个人都写“$Mode”而不是只写 $Mode?请先尝试一下再回答。
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:
This bash alterative allows for easy and concise adding of more valid values:
Why is everyone writing "$Mode" instead of just $Mode? Try it before you answer, please.