Reputation: 91
I'm currently learning bash and I'm working on loop function to recall the function if the value is not the expected.
I create a small function
#!/bin/bash
find_number(){
echo "Enter number"
read number
if [ ! $number == 1 ]; then
echo is not 1, enter number again
find_number
fi
echo "Got it"
}
find_number
If you enter a bad value it restart the function and create a loop but the only problem is that the functions loops itself and finally when it continues it returns the echo as many time as you got it wrong.
Exemple:
Enter number
5
is not 1, enter number again
Enter number
5
is not 1, enter number again
Enter number
1
Got it
Got it
Got it
As you see here I've got the result 3 times. To resolve this problem I've writtten my code in another way.
#!/bin/bash
find_number(){
echo "Enter number"
while read number; do
if [ ! $number == 1 ]; then
echo is not 1, enter number again
else
break
fi
done
echo "Got it"
}
find_number
My question is...am I doing it the right way by applying this second method or there's another way of doing it ?
thanks for your feedback
Upvotes: 1
Views: 66
Reputation: 961
You are using recursion, not loop. Try to use loop in this way:
#!/bin/bash
find_number(){
echo "Enter number"
read number
while [ ! "${number}" == "1" ]; do
echo "is not 1, enter number again"
read number
done
echo "Got it"
}
find_number
Upvotes: 0
Reputation: 8078
Since you are using recursion to 'loop', when each function finishes, you are still performing the final lines of that function as they complete.
To truly create a loop, you would use your while; do
structure to perform it properly.
Calling the function itself for recursion can create a bigger overhead if you don't have a solid base (ending) condition.
Upvotes: 1