Using some logic operators (Starting from @jimmij)
grep -q "$finding" information.txt
behaves like a boolean answer (prints nothing just has a return status of 0 if found, non-zero otherwise).
grep -F -- "$finding" ...
search text instead of regexp (remove it if you want
to search for regexp -- there may be some security risks... (thank you @StephanChazelas))
read finding
if [ -z "$finding" ]; then
echo "You didn't enter anything"
else
grep -qF -- "$finding" information.txt && echo "found" || echo "not found"
fi
or even
[ -z "$finding" ] &&
echo "nothing entered" ||
grep -qF -- "$finding" information.txt || echo "not found"
(though beware it will also run the second grep
and/or echo
if the first echo
fails)
Edit 1 > explain grep -q ...
Sure.
In normal situations, grep return status is 0 (and just returns "not 0" if an error occurs (eg. file not found))
grep -qF exp file
"returns" 0 if it finds exp in file, error otherwise (grep -q exp file
would do that if the exp
regexp was matched in file
).
This behavior can be used in bash control statements (if,elif, while, &&, ||,etc)
read f
if [ -z "$f" ]; then
echo "You didn't enter anything"
elif grep -qF -- "$f" information.txt; then
echo "found"
else
echo "not found"
fi
grep
orecho
the error message.)