Using Linux Sleep Command in Bash Scripts

This tutorial shows you how to use sleep commands and its various options in bash scripts.

Abhishek Prakash
Abhishek Prakash

Table of Contents

Linux sleep command is one of the simplest commands out there. As you can guess from the name, its only function is to sleep. In other words, it introduces a delay for a specified time.

So, if you use the sleep command with x and the next command can only be run after x seconds.

Sleep command has a simple syntax:

sleep Number[Suffix]

In here, the suffix could be:

  • s for seconds. This is the default.
  • m for minutes.
  • h for hours.
  • d for days.

Let’s see some examples of the sleep command.

Bash sleep command Examples

Though you can use it in a shell directly, the sleep command is commonly used to introduce a delay in the execution of a bash script. I am going to show the usage of sleep command through sample bash scripts.

Sleep command without suffix counts in seconds

Suppose you want pause your bash script for 5 seconds, you can use sleep like this:

sleep 5

In a sample bash script, it could look like this:

echo "Sleeping for 5 seconds…"
sleep 5
echo "Completed"

If you run it with the time command, you’ll see that the bash script actually ran for (a slightly) more than 5 seconds.

time ./ 
Sleeping for 5 seconds…

real    0m5.008s
user    0m0.000s
sys    0m0.007s

Sleep command with minute or hour or day suffix

You can specify the sleep time in minutes in the following way:

sleep 1m

This will pause the script/shell for one minute. If you want to delay the script in hours, you can do that with the h option:

sleep 2h

Even if you want to pause the bash script for days, you can do that with the d suffix:

sleep 5d

This could help if you want to run on alternate days or week days.

Sleep command with a combination of second, minute, hour and day

You are not obliged to use only one suffix at a time. You can use more than one suffix and the duration of the sleep is the sum of all the suffix.

For example, if you use the follow command:

sleep 1h 10m 5s

This will keep the script waiting for 1 hour, 10 minutes and 5 seconds. Note that the s suffix is still optional here.

Bonus Tip: Sleep less than a second

You might have noticed that the smallest unit of time in the sleep command is second. But what if your bash script to sleep for milliseconds?

The good thing is that you can use floating point (decimal points) with sleep command.

So if you want to introduce a 5 milliseconds pause, use it like this:

sleep 0.005

You can also use decimal points with other suffixes.

sleep 1.5h 7.5m

It will introduce a delay of 1 hour, 37 minutes and 30 seconds.

I hope you didn’t sleep while reading these examples of sleep command 😉

If you are interested in shell scripting, perhaps you would like reading about string comparison in bash as well. If you have questions or suggestions, please feel free to ask.

Join the conversation.