Skip to content
Advertisement

Prevent entering duplicate records in file using Shell Script

I am creating one sh file in which user enters the roll number, name, subject name and marks. And i am storing it in one text file. Now i don’t want the user to enter the same roll number again. If he enters the same roll number it should throw an message. Here is what i have done:

read -p "Enter the roll: " roll
read -p "Enter the name: " name
read -p "Enter the Subject: " sub
read -p "Enter the mark: " mark
echo "$roll $name $sub $mark" >> asd.txt

How to prevent Entering the duplicate roll number.

Advertisement

Answer

touch asd.txt
rollExists=1
while [ $rollExists != 0 ]
do
    read -p "Enter the roll: " roll
    rollExists=`grep -e "^${roll} " asd.txt | wc -l`
    if [[ "$rollExists" != "0" ]]
    then
            echo "Roll already exists"
    fi
done
read -p "Enter the name: " name
read -p "Enter the Subject: " sub
read -p "Enter the mark: " mark
echo "$roll $name $sub $mark" >> asd.txt
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement