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?
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With