Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

if [ -z "$1" ]
    echo " usage: user@host"

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

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
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"
  # do something, eg sleep for testing
  sleep 1.$i; echo $i
share|improve this answer
looks right, although i have not tested yet. thanks Peter – cwd Mar 31 '12 at 4:00

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

Your Answer


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.