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.
You were very close. You need &&
when it's not equal to.
This works:
#!/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
It gives the following output:
~ 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