Will
Will

Reputation: 29

Bash/Linux if elif else issue

Currently working on my bash skills. I've done a few activites based on if/elif/else given to me to my tutor but can't put my finger on the one below.

Basically I'm tasked with outputting the following based on the input of a grade. Less than 40% = Fail 40% to 59% = Pass 60% to 69% = Merit 70% and above = Distinction

It seems to get caught on the first elif, presents the grade as merit for anything below 70 and doesn't check the others, it gives the same result when I change the order too.

echo "Please enter your grade"
read GRADE
echo

     if [ $GRADE -ge 70 ]; then
         echo "Well done, you got a distinction"

    elif [ $GRADE -ge 60 ] || [ $GRADE -le 69 ]; then
          echo "Well done, you got a merit"
    elif [ $GRADE -ge 40 ] || [ $GRADE -le 59 ]; then
          echo "Well done, you got a pass"
    else 
          echo "Unfortunately you failed"
      fi

Upvotes: 2

Views: 783

Answers (4)

Troyan
Troyan

Reputation: 119

your problem came from the || (or), you need to use && (and). For exemple 65 is greater than 60 AND lesser than 69.

echo "Please enter your grade"
read GRADE
echo

 if [ $GRADE -ge 70 ]; then
     echo "Well done, you got a distinction"

elif [ $GRADE -ge 60 ] && [ $GRADE -le 69 ]; then
      echo "Well done, you got a merit"
elif [ $GRADE -ge 40 ] && [ $GRADE -le 59 ]; then
      echo "Well done, you got a pass"
else
      echo "Unfortunately you failed"
  fi

Upvotes: 0

clt60
clt60

Reputation: 63892

A bit unusual solution

#bash 4.0+
while read -r -p 'Grade? (h-help)> ' grade
do
    case "$grade" in
        q) echo "quitting..." ; exit 0 ;;
        h) echo "Enter numeric value (0..100) or q for quit" ;&
        '') continue ;;
        *[!0-9]*) echo "Must be numeric value" ; continue ;;
    esac
    case 1 in
        $((grade > 100)) ) echo "impossible" ;;
        $((grade >= 70)) ) echo "distinction" ;;
        $((grade >= 60)) ) echo "merit" ;;
        $((grade >= 40)) ) echo "pass" ;;
                        *) echo "fail" ;;
    esac
done

Upvotes: 1

komar
komar

Reputation: 881

There better to use -a for AND and -o for OR in []. And do something like this:

if   [ $GRADE -lt 40 ]; then
    echo "Unfortunately you failed"
elif [ $GRADE -ge 40 -a $GRADE -lt 60 ]; then
    echo "Well done, you got a pass"
elif [ $GRADE -ge 60 -a $GRADE -lt 70 ]; then
    echo "Well done, you got a merit"
else
    echo "Well done, you got a distinction"

Upvotes: 0

Senor CMasMas
Senor CMasMas

Reputation: 1

Your problem is in using || (or) rather than && (and). If you put in "10", 10 is LESS THAN 69 so it will drop into the first else.

Using set -x at the top of your script will help you figure this sort of thing out.

Upvotes: 0

Related Questions