How do I do a short delay (milliseconds) in a shell script?

I need to put a small delay into a shell script. I'm looking for something smaller than "sleep" - a second is way too long. I want to sleep something like 10 milliseconds. I've tried "usleep" and "nanosleep", but the script doesn't recognize them.

I'm using the bash shell but I'm willing to switch to a different shell if it helps to find a command that will do the delay.

Will this work for you:

typeset -i mCnt=0
while [[ ${mCnt} -le 1000 ]]; do
  mCnt=${mCnt}+1
done

You can change the number according to your CPU speed.

GNU sleep can take a number like

sleep 0.1

to sleep a fraction of a second. And since you have BASH, you're probably on a GNU/Linux system.

This has nothing to do with what shell you use, since sleep is an external utility.

it will slowing down for few millisecond.

sleep 0 

in perl try

perl -e 'select(undef,undef,undef,.1)'

I tried the "sleep 0.1" suggestion, but it says "sleep: bad character in argument".

It seems like the other suggestions are "doing it the hard way" in terms of forcing the script to do a lot of other processing to in effect slow it down. But if there's no better way to do a small delay then I'll have to resort to that.

Is it possible that you have 2 different sleeps-- a builtin and a binary? Perhaps see if /bin/sleep (or some other appropriate location...) can be called directly.

Actually, ksh has a built-in sleep which accepts a fractional argument. If the OP has ksh on his system, it may be an expedient solution.

Regards,
Alister

I've never heard about builtin sleep. It's just not GNU sleep (BSD on Mac, or something else). The variant with perl is the best solution (on modern enough boxes).

ksh93 does indeed have a built-in sleep.

GNU sleep is not special in this regard. I regularly use *BSD and every BSD's sleep(1) supports fractions of a second.

Regards,
Alister

1 Like

Oh, yes. I checked it in ksh with "which" but I should do it with "type". Too many shells, too many *nixes, too little experience... )))