Issue
I am trying to read a text file, sport.txt, which contains the following and am trying to match the user input with the sports name found in the text file.
If it's found it will print "sports found" and if it's not found it will print "No sports found".
The first example shown looks almost perfect till I tried to key in a random word and it displays an error:
[: ==: unary operator expected
I have also tried using the ""
for the variable in the second example shown, but it will just print "No sports found" even though I typed an exact sports name matches with the sports name in the text file.
File sports.txt
cycling
swimming
batmintion
Code (example 1)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [ $existingSports == $sportsName ]; then
echo "Sports Found"
else
echo "No Sports Found"
fi
If I key in 'swimming' base on the above code, the output is:
Sports Found
Now if I key in 'swim', the output is:
No Sports Found
And if I key in a random word 'asd', the output is:
[: ==: unary operator expected
No Sports Found
Code (example 2)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [ "$existingSports" == "$sportsName" ]; then
echo "Sports Found"
else
echo "No Sports Found"
fi
If I key in 'swimming' base on the above codes, the output is:
No Sports Found
Now if I key in 'swim', the output is:
No Sports Found
Code (example 3)
#!/bin/bash
file="sports.txt"
read -p "Enter a sports name": sportsName
existingSports=$(grep $sportsName $file);
if [[ "$existingSports" == "$sportsName" ]]; then
echo "Sports Found"
else
echo "No Sports Found"
fi
If I key in 'swimming' base on the above code, the output is:
No Sports Found
Now if I key in 'swim', the output is:
No Sports Found
As mentioned, the first example is almost close to the expected. What should I do to get rid of the error message?
Solution
Instead of this block:
existingSports=$(grep $sportsName $file);
if [ $existingSports == $sportsName ]; then
echo "Sports Found"
else
echo "No Sports Found"
fi
You can just utilize grep -q
with word boundaries and reduce your code to single line:
grep -q "\<$sportsName\>" "$file" && echo "Sports Found" || echo "No Sports Found"
As per man grep
:
-q, --quiet, --silent
Quiet; do not write anything to standard output. Exit immediately with zero status if any match is found, even if an error was detected.
Answered By - anubhava