Bash 脚本 - If 语句未按预期运行

Bash Scripting - If statement not behaving as intended

这是我第一次玩 bash 脚本,但我就是不明白为什么这个 if 语句不起作用。无论我将什么输入输入 choice 变量作为输入,我总是得到 returned 第一个 echo,它应该只在我输入 yes 或 no 以外的任何内容时执行。

我试过删除括号,用双引号引起来,但我就是无法理解这一点。

代码如下:

#!/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

只有最后一个 运行 应该 return 回显语句。

你们非常亲密。当它不等于时,您需要 &&。 这有效:

#!/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

它给出以下输出:

~ bash test.sh
Would you like to take driving lessons: yes
Type your age: 432
~ bash test.sh
Would you like to take driving lessons: fdsa
Type your age: 32
Your choice must be either yes or no

你应该这样写:

#!/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