I am trying to create a logon program for users listed on a file. When I try to store the names into and array and check to see if they exist, I only return the header. So if I put NAME as the fname, it says it exists. But if I put Bob as fname, it says it doesn't. How do I store each first and last name into an array?

users.txt

NAME            PASSWORD        DEPT    AUTH
Bob Jones       12345678        MKTG    N
Sam Smith       password        MKTG    Y
Pat Johnson     87654321        SALES   N
Dina Shore      drowssap        OPS     Y

Script

#!/bin/bash
FILE="users.txt" 

read -p "Please enter first and last name: " fname lname

read -a name < $FILE

for name in "${name[0]}" 

do 

    if [[ ${name[0]} = $fname ]]
    then
            echo "exist"
    else
            echo "Not Exist"
    fi
done
  • Why an array at all? – RudiC Dec 6 at 11:56
  • The assignment asks for it but I may not end up using one. – Jeff Dec 6 at 21:58

To answer your question: the single read reads the first line's (the header's) words into the array elements. No other lines are considered. You might experiment with the readarray command, but that doesn't lean itself towards your problem. YMMV

No array needed. Use adequate text tools instead. Try

#!/bin/bash
FILE="users.txt" 
read -p "Please enter first and last name: " fname lname
if grep "$fname.*$lname" $FILE
  then echo "exist"
  else echo "Not Exist"
fi
  • Thanks! I needed to match the user name with the password in the file so I did if grep "$fname.*$lname.*$psswd" $FILE and it worked great. – Jeff Dec 6 at 21:55

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.