croxfade
croxfade

Reputation: 63

Bash script looping after end of file

My bash script asks user for their first name, last name, address and phone number and writes this information that is input by the user to a file of the format "firstname.lastname"; however I want to repeat this a number of times (I actually wanted to do something like a do..while loop where it runs atleast one time and asks user if they want to continue creating accounts or not but I see there is no do...while for bash it seems). So when I execute this bash script in the terminal it will ask for how many accounts to be made and I provide all the input but the it only runs one time. What am I doing wrong? Here is my script.

#!bin/bash

echo "How many accounts are you creating?"
read num
echo "Enter first name" 
read fName
echo "Enter last name"
read lName
echo "Enter address"
read add
echo "Enter phone number"
read phn
echo "Enter gender m for male and f for female"
read gender

if [ "$gender" == "m" ]
    then
        sex="male"
elif [ "$gender" == "f" ]
    then 
        sex="female"
else 
    echo"Invalid gender. Restart the script and enter a valid gender"
    exit 0
fi
for (( i = 0; i<=num; i++))
do
    cat > $fName.$lName <<-EOF
        Full Name: $fName $lName
        Address: $add
        Phone number: $phn
        Gender: $gender
    EOF
done

Upvotes: 0

Views: 642

Answers (2)

Dolda2000
Dolda2000

Reputation: 25855

zerobandwidth's answer is correct, but as an alternative answer, it is in fact quite easy to do what you initially wanted to do:

while true; do
    # Your account creation code goes here

    echo "Create another account (y/n)?"
    read another
    if [ "$another" != y ]; then
        break
    fi
done

Upvotes: 2

zerobandwidth
zerobandwidth

Reputation: 1303

Put your input code inside the loop, or wrap that code in a function and call the function inside the loop.

Upvotes: 2

Related Questions