jfbribeiro
jfbribeiro

Reputation: 19

Verify if the email already exists - Shell Script

if [ -f users.txt ];
  a=$(cat users.txt | grep "$email" | cut -d ',' -f1 )
  then
    if [ $a -eq $email ];
      then
        echo " Your email is already registed"
        ./new_user.sh
    fi
fi

I have a file called users.txt that contains the list of all users, where the email is in the first column, and I want to verify if the email already exists... can someone help me ?

For the first time that I create a user, the file users.txt doesn't exist, that's why I'm doing if [ -f users.txt ];

Upvotes: 1

Views: 273

Answers (1)

nu11p01n73R
nu11p01n73R

Reputation: 26667

The syntax of if iss wrong. The correct syntax is

if [ condition ]
then
   body
fi

so a=$(cat users.txt | grep "$email" | cut -d ',' -f1 ) cannot be where you have written.

now if you want to check the presence of $email in users.txt the grep is only required. The second if can be rewritten

if [ -f users.txt ];
  grep  -q "$email" users.txt
  if (( $? == 0 ))
  then
        echo " Your email is already registed"
        ./new_user.sh
  fi

 fi

What it does??

grep -q "$email" users.txt matches $email in users.txt file -q is quiet so the matched lines are not printed.

$? is the exit status of previous command, here the grep will have value 0 on successfull completion, that is when there is a match.

Upvotes: 1

Related Questions