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
Braiam
  • 35,380
  • 25
  • 108
  • 167
Adam Poyser
  • 175
  • 1
  • 1
  • 6
  • 3
    What are you expecting to happen? – phemmer Sep 22 '14 at 12:42
  • It was meant to say that a string which you enter, it looks for it in the file and it says if that string is present. I've now realised that I need to enter another bit of code for else. Thanks – Adam Poyser Sep 22 '14 at 12:46
  • `input_string` isn't really a speaking variable name, by the way :) – Marian Sep 22 '14 at 17:12
  • 1
    You need double quote around variable expansions. Read [Why does my shell script choke on whitespace or other special characters?](http://unix.stackexchange.com/questions/131766/why-does-my-shell-script-choke-on-whitespace-or-other-special-characters) – Gilles 'SO- stop being evil' Sep 23 '14 at 23:02

2 Answers2

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
GMaster
  • 5,992
  • 3
  • 28
  • 32
  • 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 – Adam Poyser Sep 22 '14 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 '14 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.

Ghanima
  • 880
  • 1
  • 9
  • 19
user85015
  • 9
  • 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`. – Gilles 'SO- stop being evil' Sep 23 '14 at 23:00