Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

I'm trying to grab batches of input from a remote pipe via ssh. My script below works ok, but I would like to add some sort of check into it so that if something were to go wrong or break the loop would end if the script started running away.

How can I add in a component that would check if the loop ran, say 5 times in 3 seconds then the script would break the loop and auto terminate?

#!/bin/sh
if [ -z "$1" ]
    then
    echo " usage: user@host"
    echo
    exit
fi


while [ 1 ]
    do
    CB=`ssh $1 cat clipboardpipe`
    if [ -n "$CB" ]
        then
        echo $CB | /usr/bin/pbcopy
        echo $CB | /usr/local/bin/growlnotify
    fi
    sleep 1
done

ps: I had looked at using something like tail -f but it didn't seem to work when other programs expect input in batches. All advice is welcome.

pss: clipboardpipe is a named pipe in the home directory on the remote system.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

GNU date has nanosecond precision via %N.

every=3     # test every n'th itteration 
bsecs=0.95  # break at secs (float)
bnano=$(printf '%0.9f' "$bsecs"); bnano=${bnano/./};  
# avoid lead '0' octal clash when time slice < 1 sec
shopt -s extglob; bnano=${bnano#+(0)}  

tprev=$(date +%s%N)
for i in {1..24} ;do  # just a test loop

  if ((i%every==1)) ;then
    tnow=$(date +%s%N)
    if ((tnow-tprev>=bnano)) ;then 
        echo "Auto Break!  $every itteratons took longer than $bsecs secs"
        break
    fi
    ((tprev=tnow))
  fi
  # do something, eg sleep for testing
  sleep 1.$i; echo $i
done
share|improve this answer
    
looks right, although i have not tested yet. thanks Peter –  cwd Mar 31 '12 at 4:00
add comment

If you're on Linux, you can use the timeout command that is provided by the coreutils package.

timeout documentation

share|improve this answer
    
Hmmm ... re-reading your question, I realize my answer is a bit off topic as it doesn't really count the loop, just kills the command after a predefined period if it hadn't exited itself yet. The advantage of timeout is that it also kills the loop when a single run takes too long (eg. when a connection is dropped by a firewall). –  jippie Mar 30 '12 at 7:37
add comment

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.