Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two conditions in a bash if statement

I'm trying to write a script which will read two choices, and if both of them are "y" I want it to say "Test Done!" and if one or both of them isn't "y" I want it to say "Test Failed!"

Here's what I came up with:

echo "- Do You want to make a choice?" read choice  echo "- Do You want to make a choice1?" read choice1  if [ "$choice" != 'y' ] && [ "$choice1" != 'y' ]; then     echo "Test Done!" else     echo "Test Failed!" fi 

But when I answer both questions with "y" it's saying "Test Failed!" instead of "Test Done!". And when I answer both questions with "n" it's saying "Test Done!"

What have I done wrong?

like image 800
Andrzej Florek Avatar asked Jul 06 '12 21:07

Andrzej Florek


People also ask

Can you have two conditions in a IF statement?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.

How do you write two conditions in an if statement in Unix?

To use multiple conditions in one if-else block, then elif keyword is used in shell. If expression1 is true then it executes statement 1 and 2, and this process continues. If none of the condition is true then it processes else part.

What is && and || in shell script?

The operators "&&" and "||" shall have equal precedence and shall be evaluated with left associativity. For example, both of the following commands write solely bar to standard output: $ false && echo foo || echo bar $ true || echo foo && echo bar.


1 Answers

You are checking for the wrong condition.

if [ "$choice" != 'y' ] && [ "$choice1" != 'y' ]; 

The above statement is true when choice!='y' and choice1!='y', and so the program correctly prints "Test Done!".

The corrected script is

echo "- Do You want to make a choice ?" read choice  echo "- Do You want to make a choice1 ?" read choice1  if [ "$choice" == 'y' ] && [ "$choice1" == 'y' ]; then     echo "Test Done !" else     echo "Test Failed !" fi 
like image 153
abhshkdz Avatar answered Sep 29 '22 00:09

abhshkdz