Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question
    
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

1 Answer 1

up vote 0 down vote accepted

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
share|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
    
Thank you for answering. –  make Mar 2 '12 at 1:27
    
Sure thing, glad to help! –  icyrock.com Mar 2 '12 at 1:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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