Hack – Sleeping for less that 1 second in Shell / Bash Script

To sleep in your shell script in units of 1 second – sleep will see you right. However what if you want to sleep for less than one second, say for 200ms?

On some newer system you can do something like this and everything is fine:

sleep .2

However when I try this on my embedded busybox device I just get a response like this:

sleep .2
sleep: invalid number '.2'

So no luck there!

However there is a nice little hack using read, have a look at this:

read -p "" -t 0.2

This will wait for 200ms and then return! It waits for a line of text that never arrives, and times-out after 200ms – in effect it sleeps for 200ms. Now, if read receives a line during the 200ms it will return early, so only use it in cases where you’re sure it won’t or you might end up (temporarily) confused!

It’s not pretty but is better than nothing ;-)