How to Use Sleep Command in Bash Scripting

Last updated: April 29, 2023 | Linuxopsys

The Linux kernel interprets Bash scripts as a series of commands. It then converts them into instructions. Instructions execute immediately one after the other. What do we do if we want to delay the execution of a certain command? Why is that delay necessary for processing? In this tutorial, we will understand the sleep command and how to use it to achieve the needed pause.

What is the sleep command

The sleep command suspends the execution of the next command. We can control the amount of time, too. The use of the sleep command becomes critical when the execution of the next command depends on the successful completion of the previous one. We may need to wait for a certain amount of time before proceeding. 

We might wonder if the wait command can also perform the same action? It is not true. The sleep and the wait command are vastly different. The latter fetches the exit status of a process in the background after waiting for it to complete. Moreover, the argument accepted by the wait command can either be the PID or the job number of the process.

Syntax

sleep [number][time unit]

The time unit can be:

Time unitMeaningExample
sSleep for specified seconds.sleep 5s
mSleep for specified minutes.sleep 5m
hSleep for specified hours.sleep 5h
dSleep for specified days.sleep 5d

How to use the sleep command

The sleep command pauses the execution of the next command for a given time. It is useful for enforcing a time between the execution of two commands. This example shows us different ways of using the sleep command:

Example:

date
sleep 10s

date
sleep 1.3s

date
sleep 1m

date
sleep 1m 12.5s

date
sleep 1h

date
sleep 1d

date
bash sleep command

We have used the date command with the sleep command to delay the next execution of the date command for a given length of time. We have taken the time intervals in seconds, minutes, hours and days. The sleep command can accept floating-point numbers as well. It allows multiple values, which get added together to calculate the sleep duration.

Use cases of the sleep command

Sleep command is widely used over a loop to perform delays. It can also be used to create an alarm or delay the execution of a script.

Delaying execution of a script

We can delay the execution of a script using the sleep command. Let us assume we have a script "HelloWorld.sh" which simply echoes "Hello World". We can write a script to delay the execution of  HelloWorld.sh. 

Example:

#!/bin/bash
date
sleep 10s
date
./HelloWorld.sh
Delaying the execution of a script


We are printing the date and then sleeping for 10 seconds. After 10 seconds are over we are printing the date again. And finally we are calling the HelloWorld script. The date command is added to verify if the sleep happened for 10 seconds indeed. Moreover, it shows that the sleep command delayed the execution of the latter date command.

Create alarm

We can create an alarm using the sleep command to ask the operating system to play some music file after a certain period of time.

Example:

#!/bin/bash

sleep 1h
mpg123 skyfall.mp3
example bash script using sleep command - Create alarm

We can run this script either in the background or in the current shell. We are using mpg123 to play the mp3 file. This script will basically act as an alarm and after sleeping for one hour, it will play the music. In other words, the sleep command ensures that the mpg123 command doesn’t execute for 1 hour.

Using sleep with loops

We often club the sleep command with Bash loops to perform certain tasks repeatedly until a desired outcome has been reached.

Example:

#!/bin/bash
i=1
while [ $i -le 5 ]
do
	if ping $1 &> /dev/null
	then
		echo "$1 is online"
		break
	else
		echo "Attempt $i: Ping to $1 is unsuccessful. Sleeping for 10s …"
	fi
    	sleep 10
i=$((i+1))
	echo "Could not ping $1 even after $i attempts"
done
bash sleep with loops

We are using the sleep command in a loop to determine whether a website is up or not. The script tries to ping the website in 5 attempts. If it is successful, it will break out of the loop and display that the website is up. If the ping fails, the sleep command induces a 10-second delay between unsuccessful pings. Even after 5 attempts, if the ping is unsuccessful, the script will terminate.

Estimate delays

With the sleep command we can figure out the latency of execution of certain commands.

Example:

#!/bin/bash
for (( i = 1 ; i <= 15 ; i++ )); 
do
    sleep 1
    date +"%T.%3N"
    sh HelloWorld"{$i}".sh
done
checking latency of execution of certain commands

The script tells us how sleep gives the CPU ample time to perform the necessary computations before the next iteration. We can see the amount of time the script takes to run the next script. If the script being called is heavy and requires more time for execution, the latency will be more. This process is dependent on the processors and how quickly the OS can compute.

Best practices for using the sleep command

  • The sleep command accepts the default unit of time in seconds. Hence, we are not required to specify a unit if we use seconds.
  • We can have more than one argument to the sleep command. All these arguments will internally get converted into seconds.
  • Even though Bash doesn’t support floating point numbers, we can have floating point numbers with the sleep command.
  • We should have some amount of sleep if we want to build an automation script with retry mechanism.
  • We should simulate a delay in command execution to test timeout scenarios like the ping command, which we saw above.
  • To verify if the scripting is pausing as expected, we can put the date command before and after the sleep command.
  • We should not use the sleep command unnecessarily and have a precise delay to avoid excessive delays.

Bash Sleep time

We can supply the sleep interval in seconds, minutes, hours or days. If we require any other unit of time, we can convert it into any of these accordingly. We can also provide the number as floating-point or can even use the scientific 'e' notation. We have the option to supply multiple values. If time units are present, sleep converts them into the standard time unit of seconds. They are then added internally. This becomes the final sleep duration of the command.

CommandDescription
sleep .5Delay for 0.5 seconds.
sleep 0.005Delay for 5 milliseconds.
sleep 5e-3Delay for 5 milliseconds.
sleep 5Delay for 5 seconds.
sleep 1.5sDelay for 1.5 seconds.
sleep 5sDelay for 5 seconds.
sleep 5mDelay for 5 minutes.
sleep 5hDelay for 5 hours.
sleep 5dDelay for 5 days.
sleep 1m 5sDelay for 1 minute and 5 seconds.
sleep 1h 5m 5sDelay for 1 hour 5 minutes and 5 seconds.
sleep 1d 5 h 5m 5sDelay for 1 day, 5 hours, 5 minutes and 5 seconds.

Conclusion

  • The sleep command enables us to pause the execution of the following command for a fixed interval of time.
  • It is often used with loops to repeat a certain set of events.
  • It enables us to run operations in the correct order.
  • It accepts arguments in days, hours, minutes as well as seconds but it ultimately converts everything into seconds before executing.
SHARE

Comments

Please add comments below to provide the author your ideas, appreciation and feedback.

Leave a Reply

Leave a Comment