0

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.

SneakyShrike
  • 723
  • 1
  • 10
  • 31
  • 2
    Combining negative tests can be unintuitive. [De Morgan's laws](https://en.wikipedia.org/wiki/De_Morgan%27s_laws) explain why this doesn't work. – Gordon Davisson Jun 01 '22 at 10:58

2 Answers2

2

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
Mikael Kjær
  • 670
  • 3
  • 6
0

You should write it like this:

#!/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
Ivan
  • 96
  • 8