Tejendra
Tejendra

Reputation: 1944

Does editing a file while some script is performing grep in it has any effect

Well I am trying to take some decision based on some text is not present in a file, but the problem is the file will be modified while my shell script is doing grep in it.

#!/bin/bash
grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
while [ $ret_code -ne 0 ]
do
  echo $ret_code
  grep -q "decision" /home/tejto/test/testingshell
  echo 'Inside While!'
  sleep 5
done
echo 'Gotcha!'

The text "decision" is not present in file while this shell script is started, but when I modify this file by some other bash prompt and put the text 'decision' in it, in this case my script is not taking that change and it is keep on looping in while , so does that mean my shell script caches that particular file ?

Upvotes: 3

Views: 94

Answers (1)

anubhava
anubhava

Reputation: 786289

Because you are setting ret_code variable only once outside loop and not setting it again inside the loop after next grep -q command.

To fix you will need:

grep -q "decision" /home/tejto/test/testingshell
ret_code=$?
while [ $ret_code -ne 0 ]
do
  echo $ret_code
  grep -q "decision" /home/tejto/test/testingshell
  ret_code=$?
  echo 'Inside While!'
  sleep 5
done
echo 'Gotcha!'

OR you can shorten your script like this:

#!/bin/bash

while ! grep -q "decision" /home/tejto/test/testingshell
do
  echo $?
  echo 'Inside While!'
  sleep 5
done
echo 'Gotcha!'

i.e. no need to use a variable and directly use grep -q in your while condition.

[EDIT:Tejendra]

#!/bin/bash

    until grep -q "decision" /home/tejto/test/testingshell
    do
      echo $?
      echo 'Inside While!'
      sleep 5
    done
    echo 'Gotcha!'

This last solution would not use ret_code and give the desired result as first solution.

Upvotes: 1

Related Questions