If user input matches file contents

I was wondering how I can read values from a file and then proceed if those values
match a user input. For example (a simple one), a user inputs their name, then we check if that name is in a file of usernames. If it is, it says proceed, if not, then it says you are not authorized.

userlist=`cat /home/user1/user_list.txt`
echo "Enter your username:"
read username
if [[ $username = $userlist ]];then
    echo "You may proceed"
else
   echo "You are not authorized"
exit
fi

userlist.txt:

bjames
jbryant

One way to achieve this is using grep command:

echo "Enter your username:"
read username
if [[ $( grep -c "$username" userlist.txt ) -ne 0 ]]; then
   echo "You may proceed"
else
   echo "You are not authorized"
   exit 1
fi

You can simplify that a bit:

if grep "$username" filename.txt >/dev/null
then
...
fi
if grep -Fxq "${username:-noname}" filename.txt
then

Thank you all for your solutions. Problem solved. :slight_smile:

You're welcome. Make sure to test what happens when you enter an empty string, or a single dot, or just the letter b, or "james", or special characters, for example...