1

The problem is wait for a file to get updated, but not indefinitely. So I want to check if a file has certain contents as -

while ! grep -q $contents  /path/to/file
do
  sleep $timer
done

along with it I want to check if the timer has expired, say $timer == 0. Here we want the response in the return value so that I can combine with another command using && like

! grep -q $contents /path/to/file && ls someFile 

Then the return codes gets fed into if and the need of a temporary variable is removed.

I am currently doing it in this way but I am looking to do it in the while statement itself:

# Wait for 16, 8, 4, 2, 1 seconds each to check for progress
waitTime=16
while ! grep -q $contents $LOG_FILE
do
  sleep $waitTime
  waitTime=$((waitTime/2))
  if [ $waitTime -eq 0 ]
  then
    break
  fi
done
user 923227
  • 2,528
  • 4
  • 27
  • 46
  • Did I correctly parse your question as being "how do I poll for whether a condition is true for up for a certain amount of time"? If not, could you clarify how my interpretation differs from what you meant to ask? (And if so, do you mind if I edit your question to more clearly reflect the intended focus?) – Charles Duffy Sep 19 '17 at 22:03
  • Yes, you got it right. But I am looking to see if this can be done in a way that the test result is returned as a return-value `$?` so that it sits in the while loop condition itself. – user 923227 Sep 19 '17 at 23:33
  • All operations have an exit status. `[ $waitTime -eq 0 ]` -- which you're already performing -- has one too. – Charles Duffy Sep 19 '17 at 23:44

1 Answers1

2

For a mathematical expression, use (( )) to evaluate it in arithmetic context.

#!/usr/bin/env bash
#              ^^^^- not /bin/sh; (( )) -- vs $(( )) -- is a bashism.

waitTime=16
while (( waitTime )) && ! grep -q -e "$contents" /path/to/file; do
  sleep "$waitTime"
  waitTime=$(( waitTime / 2 ))
done

Here, (( waitTime )) has an exit status of 0 if and only if the value of waitTime is a positive integer.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441