0
read X
read Y
read Z

if [ $X = $Y = $Z ]
    then
        echo EQUILATERAL # ALL X, Y, Z ARE EQUAL
        
elif [[ $X = $Y || $X = $Z || $Y = $Z ]]
    then
        echo ISOSCELES # ONLY 2 VARIABLES ARE EQUAL
    
else
    echo SCALENE # NONE IS EQUAL
fi

Well, I have two questions here, first is the usage of $X = $Y = $Z valid or not. Second, when I give an input of 3 similar variables it's printing ISOSCELES instead of EQUILATERAL. Is it a logic error, or the first part is not syntactically correct?

6
  • 3
    Bash has nothing like [ $X = $Y = $Z ] You need [ "$X" = "$Y" ] && [ "$Y" = "$Z" ] Always post your code to ShellCheck to fix minor issues like this first, then if you still have problems, post here. Commented Jul 28, 2022 at 6:25
  • Don't ask two question in one post. Use separate posts, in particular since your second question does not make sense, unless the first has been solved: Your program won't print what you describe in your question, but simply throw an error message bash: [: too many arguments because of the erroneous if statement. Commented Jul 28, 2022 at 6:41
  • you missed some possibilties: what types are (x=1,y=1,z=2) or (x=1,y=1,z=3)? Commented Jul 28, 2022 at 10:26
  • @DavidC.Rankin you probably can turn your comment into an answer here? Since this is essentially what OP is asking about Commented Jul 28, 2022 at 15:03
  • @TheDreamsWind - why don't you go ahead and write it up. A good collection from the comments, including the tip about ShellCheck will make a nice answer for this question. I'd just start out with "You have the following syntax errors in your code. (bullet A, B, C)", and then explain what bash requires (including the requirement to double-quote within [ ... ] or with test (synonymous). If you need a reference I like the man7.org pages, e.g. man 1 bash Commented Jul 28, 2022 at 20:02

1 Answer 1

1

According to Bash Syntax and to what I understood. We can't compare multiple variables with one variable at the same time. So, we would open multiple condition checks [] for each comparison: I changed [ $X = $Y = $Z ] To [ "$X" = "$Y" ] && [ "$Y" = "$Z" ]

#!/bin/bash

read -r X
read -r Y
read -r Z

if [ "$X" = "$Y" ] && [ "$Y" = "$Z" ]
    then
        echo EQUILATERAL # ALL X, Y, Z ARE EQUAL
        
elif [[ $X = "$Y" || $X = "$Z" || $Y = "$Z" ]]
    then
        echo ISOSCELES # ONLY 2 VARIABLES ARE EQUAL
    
else
    echo SCALENE # NONE IS EQUAL
fi
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.