bash脚本 - 如果语句不按预期行为
这是我第一次玩Bash脚本,但是我只是不明白为什么如果语句不行为。无论我输入哪个输入,作为输入,我总是会返回第一个回声,只有在我输入Yes或否以外的任何其他内容时才能执行。
我尝试删除括号,用双引号封闭,但我对此无法理解。
这是代码:
#!/bin/bash
read -p 'Would you like to take driving lessons: ' choice
read -p 'Type your age: ' age
if [ $choice != 'yes' ] || [ $choice != 'no' ]
then
echo 'Your choice must be either yes or no'
fi
这是输出:
$ ./test.sh
Would you like to take driving lessons: yes
Type your age: 46
Your choice must be either yes or no
$ ./test.sh
Would you like to take driving lessons: no
Type your age: 63
Your choice must be either yes or no
$ ./test.sh
Would you like to take driving lessons: dgdgf
Type your age: 76
Your choice must be either yes or no
只有最后一个运行才能返回回声语句。
This is my first time playing with bash scripting, but I just cannot understand why this if statement is not behaving. No matter what input I enter into the choice variable as input I always get returned the first echo which should only execute if I input anything other than yes or no.
I've tried removing brackets, enclosing in double quotes, but I just can't make sense of this.
Here is the code:
#!/bin/bash
read -p 'Would you like to take driving lessons: ' choice
read -p 'Type your age: ' age
if [ $choice != 'yes' ] || [ $choice != 'no' ]
then
echo 'Your choice must be either yes or no'
fi
Here is the output:
$ ./test.sh
Would you like to take driving lessons: yes
Type your age: 46
Your choice must be either yes or no
$ ./test.sh
Would you like to take driving lessons: no
Type your age: 63
Your choice must be either yes or no
$ ./test.sh
Would you like to take driving lessons: dgdgf
Type your age: 76
Your choice must be either yes or no
Only the last run should return the echo statement.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你很近。当它不等于时,您需要
&
。这起作用:
它给出以下输出:
You were very close. You need
&&
when it's not equal to.This works:
It gives the following output:
您应该这样写:
You should write it like this: