2

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.

  • What's your definition of "not containing a string"? Do you mean that the output returns numbers only? – Carlos Mar 2 '12 at 0:32
  • a given string. – make Mar 2 '12 at 1:04
9

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
| improve this answer | |
  • Could you change that until it doesn't contain the string? – make Mar 2 '12 at 1:14
  • Sure - just use if [[ ! $str =~ 5 ]]; then instead, see my edit. – icyrock.com Mar 2 '12 at 1:21
  • bash-2.05$ conditional binary operator expected line 4: syntax error near unexpected token `=~' if [[ ! $str =~ 'NOT successful' ]]; then – make Mar 2 '12 at 1:25
  • Sure thing, glad to help! – icyrock.com Mar 2 '12 at 1:33
  • Do you know how to fix the error above? I think it's related to version 2.05 of bash installed on this system. – make Mar 2 '12 at 1:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.