Alright i'm having problems with this loop. Basically once the script is ran a parameter is required. Once entering the parameter it displays that in LIMIT. Alright so now the problem, I need my loop to ask my user for a number, and if that number is less than the limit then sum the input values until it reaches the limit.
example output of what i need
LIMIT = 50
please enter a number: 10
I = 10 SUM = 10
please enter a number: 15
I = 15 SUM = 25
please enter a number: 20
I = 20 SUM = 40
please enter a number: 15
done!
this is the code i have so far, the SUM PART is messed up and i dont know how to exit the loop and display done once it reached the limit.
#!/bin/sh
if [ $# -ne 1 ]; then
echo "usage: help.sh LIMIT"
exit
fi
LIMIT=$1
echo "LIMIT =" $LIMIT
read -p"Please enter a number: " I
echo "I =" $I "SUM =" $I
while [ $I -le $LIMIT ]
do
read -p"Please enter a number: " X
echo "I =" $X "SUM =" `expr $I + $X`
done
I am still not able to figure out the requirement. But if you want to come out of the loop then give the input greater than 50 because this is the LIMIT which you have set in the beginning. The while loop will check this input value with the LIMIT value and since the value is greater than 50 so it wont go inside the loop again.
For displaying "done", you can use echo or print command after the while loop.
If this is not what you want then please help me understand the requirement.
To run the script.
help.sh
it will display that you need to specify a parameter which is limit
so in this case.
help.sh 50
LIMIT = 50
please enter a number: 10
I = 10 SUM = 10
please enter a number: 15
I = 15 SUM = 25
please enter a number: 20
I = 20 SUM = 45
please enter a number: 15
I = 15 SUM = 60
done!
So once entering the limit, it will prompt you to enter a number until you reach that limit, and once reaching that limit it displays done. I cant get the sum to add up correctly, this is what i'm getting.
help.sh 50
LIMIT = 50
please enter a number: (enter number 10)
I = 10 SUM = 10
please enter a number: (enter number 15)
I = 15 SUM = 25
please enter a number: (enter number 20)
I = 20 SUM = 30 (should be 45)
etc.
Its just adding 10 to I each time and displaying it in SUM.
The variables are not used correctly, so give this a try instead :
#!/bin/sh
#set -x
if [ $# -ne 1 ]; then
echo "usage: help.sh LIMIT"
exit
fi
LIMIT=$1
echo "LIMIT =" $LIMIT
SUM=0
while [ $SUM -lt $LIMIT ]
do
read -p "Please enter a number: " I
SUM=`expr $SUM + $I`
echo "I = $I and SUM = $SUM"
done