Having trouble greping a variable

I'm trying to take a users input, and then such a text file to see if it contains it.
I get an error when running it:
"./Login.sh: Line 8: [grep: command not found
Failed to login."

echo Username
read username

if [grep $username register.txt ]; then
echo Login successful.
else
echo Failed to login.
fi

If someone could give me some input to where I'm going wrong it'd be greatly appreciated.

you don't need to use [ ] at all. but the problem is that you need a space after '['. if takes a command. grep is a command. you can simply use grep there.

if grep -q "$username" register.txt; then
1 Like
 
echo Username
read username
grep $username register.txt > /dev/null 2>&1
if [ "$?" -eq "0" ]; then
echo Login successful.
else
echo Failed to login.
fi

$? is a speacial variable which holds the exit code of the previous command.

so, if the grep is success, then it is 0 otherwise not zero

1 Like

This worked, thank you.

Check if you have the -q flag for grep so no output is produced. That is a neater way of writing it. You may need to check you can read the file first though:-

if [ -r register.txt ]
then
   grep -q $username register.txt
   RC=$?
else
   echo "Cannot read file"
   RC=99
fi

if [ $RC -eq 0 ]
then
   echo "Login successful."
else
   echo "Failed to login."
fi

you have also tried to use the numeric test -eq to compare two strings, so results can be unpredictable on different platforms. As we are sure that 0 is numeric, don't quote it. Similarly, RC will always be numeric.

I hope that this is useful.

Robin
Liverpool/Blackburn
UK

1 Like