10

Why my code isn't outputting if a string entered isn't in the file. When I enter a string and it isn't in the file, there's no response back, it re-loops back to the beginning. Can someone tell me what's wrong with my code?

while :
do
echo "Please enter a string"
read input_string
echo "Please enter the file name too see if that string is present in it - (Enter .abw after)"
read input_string1
if grep -q $input_string $input_string1 ; then
echo  "Your string has been found"
fi
done
4

2 Answers 2

10
while :
 do
     echo "Please enter a string"
     read input_string
     echo "Please enter the file name too see if that string is present in it - (Enter .abw after)"
     read input_string1
     grep -q "${input_string}" "${input_string1}"                                                                 
     if [ $? -eq 0 ] ; then
         echo  "Your string has been found"
     else 
         echo "Your string has not been found"
     fi
 done
2
  • 1
    I've just tried this code and it works thanks! I didn't realise that all my problem was with not having an else statement. Thanks for the quick response Sep 22, 2014 at 12:53
  • 2
    You need to quote grep parameters. Think what would happen if my search string includes -v, or there are spaces in the filename.
    – Ángel
    Sep 22, 2014 at 19:33
0

You figured out your missing else-branch, but one suggestion:

instead of using $input_string $input_string1 try ${input_string} ${input_string1} just to make sure you don't get $input_string followed by 1.

1
  • No, your proposed replacement is exactly equivalent to the original. $input_string1 is the value of the variable input_string1 (split and globbed, since it isn't quoted), it doesn't involve the variable input_string. Sep 23, 2014 at 23:00

Not the answer you're looking for? Browse other questions tagged .