I am preparing shell code for comparing 3 numbers. My code is as follows
#!/bin/bash
echo "enter any 3 numbers"
read num1
read num2
read num3
if [ $num1 -gt $num2 ]
then
if [ $num1 -gt $num3 ]
then
echo "$num3 is greater than $num1 & $num1"
fi
elif [ $num2 -gt $num1 ]
then
if [ $num2 -gt $num3 ]
then
echo "$num2 is greater than $num1 & $num3"
fi
elif [ $num3 -gt $num1 ]
then
if [ $num3 -gt $num2 ]
then
echo "$num3 is greater then $num2 &$num1"
fi
else
echo "invalid"
fi
if i put 1st or 2nd highest number then it is giving right output,But in case if i put 3rd higest number it is not evaluating.Second elif statement is not getting evaluated.
CodePudding user response:
Let's make this more readable first:
if [ $num1 -gt $num2 ]; then
if [ $num1 -gt $num3 ]; then
echo "$num1 is greater than $num2 & $num3" # typos fixed
fi
elif [ $num2 -gt $num1 ]; then
if [ $num2 -gt $num3 ]; then
echo "$num2 is greater than $num1 & $num3"
fi
elif [ $num3 -gt $num1 ]; then
if [ $num3 -gt $num2 ]; then
echo "$num3 is greater then $num1 & $num2" # typos fixed
fi
else
echo "invalid"
fi
If you enter e.g. num1 == 1
, num2 == 2
, num3 == 3
, then it won't work because this is true:
elif [ $num2 -gt $num1 ]; then
but after that, this is false:
if [ $num2 -gt $num3 ]; then
thus there is no output. Execution will not continue with elif [ $num3 -gt $num1 ]; then
if that is what you expected, ifs don't work like that.
You could restructure it like this:
if [ $num1 -gt $num2 ] && [ $num1 -gt $num3 ]; then
echo "$num1 is greater than $num2 & $num3"
elif ...
and continue adding elif
s until all possible permutations and cases are covered.
CodePudding user response:
This is a lot simpler if you just make two comparisons at once:
if [ "$num1" -gt "$num2" ] && [ "$num1" -gt "$num3" ]; then
echo "$num1 is greater than $num2 and $num3"
elif [ "$num2" -gt "$num1" ] && [ "$num2" -gt "$num3" ]; then
echo "$num2 is greater than $num1 and $num3"
elif [ "$num3" -gt "$num1" ] && [ "$num3" -gt "$num2" ]; then
echo "$num3 is greater than $num1 and $num2"
# else echo "no one number is biggest"
fi