Hey Guys,

I am a newb when it comes to bash scripting,but I am loving the learning so far. I am at a wall though. I have scoured for hours tryng to find an answer.

Basically here is the pseudo code:
1. ask for users grade 3 times in using a loop.
2. Calculate the users number grade to a letter grade.
3. Print back average grade using the letter that corresponds.

Any ideas of how I can declare the users input as a unique variable each time and then store it until I calculate at the end?


This is what I have:
--------------------------------------------

#!/bin/bash


function LetterGrade ()
{
if [[ $GRD -gt "89" ]]
 then
	echo "A score of" $GRD "is an A"
else
	if [[ $GRD -gt "79" ]]
 then
	echo "A score of" $GRD "is a B"
else
	if [[ $GRD -gt "69" ]]
 then
	echo "A score of" $GRD "is a C"
else
	if [[ $GRD -gt "59" ]]
 then
	echo "A score of" $GRD "is a D"
else
	if [[ $GRD -lt "60" ]]
 then
	echo "A score of" $GRD "is an F"

fi
fi
fi
fi
fi
}

echo "Grade Application-Week 4 Indiv. Assignment"

for (( c=1; c<=3; c++))
do

read -p "Please insert Grade #$c:" GRD
LetterGrade $GRD
echo
done

Sum=`expr $GRD1 + $GRD2 + $GRD3 `
AvgGrd=`expr $Sum / 3 `

echo "Sum of all grades entered of: $GRD1, $GRD2, and $GRD3 is $Sum"
echo "Average of grades entered of: $GRD, $GRD, and $GRD is $AvgGrd"
LetterGrade $AvgGrd;
echo
-----------------------------------------------

... Any ideas of how I can declare the users input as a unique variable each time and then store it until I calculate at the end?

#!/bin/bash
...
for (( c=1; c<=3; c++))
do

read -p "Please insert Grade #$c:" GRD$c
LetterGrade $GRD
echo 
done
...

One way to do it is to put $c after the variable you are reading. Of course, then you have to change the rest of your code to deal with these vars.

Another way to do it is use use arrays, which should be illustrated in the man page.

N

Hey There,

Another way to go about it would be to do the math incrementally, within the loop, to avoid any possibility of losing the variables value when you exit the loop due to scope issues. You can do this by using $c as your counter variable, as well, so you don't run your function until all 3 answers have been received

For instance:

for (( c=1; c<=3; c++))
do

read -p "Please insert Grade #$c:" GRD1
let GRD=$GRD+$GRD1
if [ $c -eq 3 ]
then
LetterGrade $GRD
echo 
fi
done

Best wishes,

Mike

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.