Can anyone help me with my code? When I run my script I always get Grade F.
#!/bin/bash
echo "Enter your percentage to see grade letter"
read grade
if [ $grade -ge 60 ]; then
echo "Your Grade F"
elif [ $grade -ge 60 ] || [ $grade -le 69 ]; then
echo "Your grade D"
elif [ $grade -ge 70 ] && [ $grade -le 79 ]; then
echo "Your grade C"
elif [ $grade -ge 80 ] && [ $grade -le 89 ]; then
echo "Your grade B"
elif [ $grade -ge 90 ] && [ $grade -le 100 ]; then
echo "Your Grade is A"
else
echo "try again"
fi
CodePudding user response:
You have a logic error in your code. Your first test is wrong. It tests all values that are greater than or equal to 60, and makes them an F. This prevents the rest of the tests from happening for those values.
Your second test is also wrong; you're using an OR (||) instead of an AND (&&).
Your last test could be reduced, because all values greater than or equal to 90 are an A, so the second test isn't necessary.
I personally would test for the higher vales and work down if I was writing the code, but that's your choice. The below should work.
#!/bin/bash
echo "Enter your percentage to see grade letter"
read grade
if [ $grade -le 59 ]; then
echo "Your Grade F"
elif [ $grade -ge 60 ] && [ $grade -le 69 ]; then
echo "Your grade D"
elif [ $grade -ge 70 ] && [ $grade -le 79 ]; then
echo "Your grade C"
elif [ $grade -ge 80 ] && [ $grade -le 89 ]; then
echo "Your grade B"
elif [ $grade -ge 90 ]; then
echo "Your Grade is A"
else
echo "try again"
fi
CodePudding user response:
Here's how I'd do it.
#!/bin/bash
# Get the grade
read -rp "Enter your percentage to see grade letter: " grade
# Test the input to make sure it's a number,
# and exit with an error message if it isn't
[[ "$grade" =~ ^[0-9] $ ]] || { echo "Please enter an integer." ; exit; }
# Test the number, print the grade, and exit
[[ "$grade" -le 49 ]] && { echo "You want to go home and re-think your life." ; exit; }
[[ "$grade" -le 59 ]] && { echo "Your Grade: F" ; exit; }
[[ "$grade" -le 69 ]] && { echo "Your grade: D" ; exit; }
[[ "$grade" -le 79 ]] && { echo "Your grade: C" ; exit; }
[[ "$grade" -le 89 ]] && { echo "Your grade: B" ; exit; }
[[ "$grade" -ge 90 ]] && { echo "Your Grade: A" ; exit; }
I'm not sure if it's more or less efficient than using if-elif-fi
or case
. I'm sure it's not as pretty. But it only tests $grade
until it gets a hit and then it stops, and something about that appeals to me.
I was tempted to put the "Is this a number?" test in a loop so you wouldn't have to invoke the script again if you flubbed the input, but I resisted the temptation.
(I'm a rookie with bash scripting, so I welcome criticism.)