Hack Forums
[Shell] Breaking out of bash loop when condition is met - Printable Version

+- Hack Forums (https://hackforums.net)
+-- Forum: Tech (https://hackforums.net/forumdisplay.php?fid=444)
+--- Forum: Coding (https://hackforums.net/forumdisplay.php?fid=151)
+---- Forum: Software Development (https://hackforums.net/forumdisplay.php?fid=118)
+---- Thread: [Shell] Breaking out of bash loop when condition is met (/showthread.php?tid=6016658)



Breaking out of bash loop when condition is met - friiz1337 - Oct 15, 2019

Hey guys, I'm trying to figure out how to break out of a loop when the user types the correct username. For now my loop continues to give me the same "Try again" output even when the condition is correct. I tried with 2 loops but it didn't work. Any ideas?
Code
if [ "$userResult" == 1 ]
then
echo Enter password:
read password
else
echo Wrong username. Try again:
read username
while [ "$userResult" == 0 ]
do
echo try again:
read username
done
fi
When username is correct the first time:
Code
Enter Username
BOBO
Enter password:
When username is correct the 2nd time:
Code
Enter Username
B
Wrong username. Try again:
BOBO
try again:



RE: Breaking out of bash loop when condition is met - realsunjester - Oct 18, 2019

Code
#!/bin/bash
echo -n "please type your name: "
read name
while [ "$name" != "sunjester" ]
do
        read name
        echo -n "please type your name: "
done

still buggy but have fun.


RE: Breaking out of bash loop when condition is met - friiz1337 - Oct 18, 2019

(Oct 18, 2019 02:13 AM)realsunjester Wrote:  
Code
#!/bin/bash
echo -n "please type your name: "
read name
while [ "$name" != "sunjester" ]
do
       read name
       echo -n "please type your name: "
done

still buggy but have fun.

It doesn't work in my case as the username that is being read is either a 1 or a 0 (output from mysql). Basically if the user is found in the database return 1, else 0.

(Oct 18, 2019 04:45 AM)friiz1337 Wrote:  It doesn't work in my case as the username that is being read is either a 1 or a 0 (output from mysql). Basically if the user is found in the database return 1, else 0.

Fixed it by using a function that calls the username. If anyone is also interested in knowing how to fix this problem, PM me.