Bash – Loop bash command until output no longer contains a string

bash

How to loop bash command until output no longer contains a string and then print the time the loop was stopped to output? watch command isn't available.

Best Answer

Here's an example of running date +%S, which prints seconds part of the current time, every half a second and stops on a condition (see below):

while true; do
  str=`date +%S`
  echo Output: $str
  # Use the below when you want the output not to contain some string
  if [[ ! $str =~ 5 ]]; then
  # Use the below when you want the output to contain some string
  # if [[ $str =~ 7 ]]; then
    break
  fi
  sleep .5
done
echo Finished: `date`

The condition stop:

  • If you uncomment this line only:

    if [[ ! $str =~ 5 ]]; then
    

    it will loop while 5 exists in the output (e.g. while from 50 till 00)

  • If you uncomment this line only:

    if [[ $str =~ 7 ]]; then
    

    it will loop until 7 exists in the output (i.e. until current seconds = 07, 17, 27, 37, 47 or 57)

Sample output for not containing string (5 in this case):

Output: 56
Output: 57
Output: 57
Output: 58
Output: 58
Output: 59
Output: 59
Output: 00
Finished: Thu Mar 1 20:16:00 EST 2012

Sample output for containing string (7 in this case):

Output: 08
Output: 09
Output: 09
Output: 10
Output: 10
Output: 11
Output: 11
Output: 12
Output: 12
Output: 13
Output: 13
Output: 14
Output: 14
Output: 15
Output: 15
Output: 16
Output: 16
Output: 17
Finished: Thu Mar 1 19:58:17 EST 2012
Related Question