5 Examples of Using the sleep Command in Linux

Try this guide with our instant dedicated server for as low as 40 Euros

When a user initiates a sequence of multiple commands in Linux, the commands typically execute sequentially or concurrently, as seen with commands like tee

Yet, there are instances where delaying the execution of commands becomes essential. In these scenarios, you need to provide an interval between command executions. It is here the sleep command comes as a perfect solution to handle these scenarios. For instance, you can pause your Linux scripts, ensuring everything happens when it should.

In this tutorial, you’ll discover how to effectively utilize the Linux sleep command to introduce delays in command execution in terminal environments and shell scripts. But first, let’s do a quick dive into the Linux sleep command.

Table Of Contents

  1. What is the Linux sleep Command?
    1. An Overview of Linux Sleep Command Syntax
  2. 5 Examples of Using the sleep Command
    1. The Prerequisites
    2. Example #1: Set an Alarm
    3. Example #2: Delay Command Execution in the Terminal
    4. Example #3: Assign a Variable to the sleep Command
    5. Example #4: Define Website Check Intervals
    6. Example #5: Anticipate Latency
  3. Conclusion
  4. FAQs

What is the Linux sleep Command?

The sleep command halts the execution of the subsequent command for a designated duration. 

It introduces a pause in scripts before moving into the execution of the next command. This feature is crucial when the execution of the following commands relies on the successful completion of a preceding one. 

The default time interval of the sleep command is seconds. However, you can change this default and set the delay window in minutes, hours, and days. 

An Overview of Linux Sleep Command Syntax

The following basic syntax of the sleep command is simple and allows one to easily introduce pauses within the shell script:

# sleep [number]

Consider the following command that pauses execution for five seconds.

# sleep 5

sleep 5

As mentioned before, by default, the system interprets the number following sleep as seconds. To designate alternative time units, utilize the following syntax:

# sleep [number][unit]

Here the unit can be: 

  • s – seconds
  • m – minutes
  • h – hours
  • d – days

The sleep command supports floating-point numbers and permits the inclusion of multiple values, which are cumulatively added to determine the duration of sleep. For instance, consider the following command that introduces an interval of an hour, two minutes, and a half second.

# sleep 1h 2m 0.5s

sleep 1h 2m 0.5s

There are cases when you need to interrupt the sleep process and exit before the designated time (due to any unexpected critical system messages or script modifications). You can press Ctrl + C to interpret the sleep command.

For more assistance with the sleep command, enter:

# sleep --help 

You can print the version information about the command by running the following command:

# sleep --version

5 Examples of Using the sleep Command

Let’s see the sleep command in action. 

The Prerequisites

Before diving in, ensure you have the following,  

  • A system running a mainstream Linux distribution
  • A user account with sudo or root privileges

Example #1: Set an Alarm

A good example of the capabilities of the sleep command is to instruct the system to play an MP3 file after a specified duration. Note that this example uses MPlayer. So, if you don’t have it on your system, we recommend installing using the sudo apt install mplayer command. 

Next, run the following command to play the MP3 as an alarm after an interval of seven and a half hours using MPlayer to play the alarm.mp3 file:

# sleep 7h 30m && mplayer alarm.mp3

Example #2: Delay Command Execution in the Terminal

sleep is a great option for introducing a time interval between the execution of two commands. The following example ensures that echo commands are executed at one-second intervals.

# sleep 1 && echo "one" && sleep 1 && echo "two"

sleep 1 echo one sleep 1 echo two

Here, sleep 1 pauses the execution for one second.

&& acts as a logical AND operator. 

echo “one” prints the message one to the terminal.

sleep 1 executes a one-second pause again.

echo “two” prints the message two to the terminal.

Example #3: Assign a Variable to the sleep Command

Assigning a variable to the sleep duration allows one to easily modify the script’s behavior without editing the sleep command statement. It is also an essential step to improve script readability, maintainability, and reusability.

Here is a sample script:

#!/bin/bash

SLEEP_INTERVAL="30"

CURRENT_TIME=$(date +"%T")

echo "Time before sleep: ${CURRENT_TIME}"

echo "Sleeping for ${SLEEP_INTERVAL} seconds"

sleep ${SLEEP_INTERVAL}

CURRENT_TIME=$(date +"%T")

echo "Time after sleep: ${CURRENT_TIME}"

Here, the script sets up the variable SLEEP_INTERVAL, which is subsequently passed to the sleep command. The output of this script illustrates that the execution lasted for 30 seconds.

The CURRENT_TIME variable captures the current time with the (date +”%T”) statement that combines the date command with the +%T format specifier.

The echo commands print the messages before and after sleep. These messages print the current time retrieved earlier and after the sleep duration defined in the variable.

timescript.sh

Example #4: Define Website Check Intervals

The sleep command is not just used to delay command execution, set alarms, and improve and modify script behavior but also to check a website’s availability. 

We recommend the following example that demonstrates the application of the sleep command in a script that checks a website’s online status. 

The script halts if it successfully pings the website, with sleep introducing a 10-second delay between unsuccessful attempts.

#!/bin/bash

while :

    do

        if ping -c 1 www.google.com &> /dev/null

        then

        echo "Google is online"

        break

        fi

    sleep 10

done

hostscript.sh

Here while: initiates an infinite loop. 

if ping -c 1 www.google.com &> /dev/null; then checks if Google’s website is online and then defines what happens if the ping command is successful (

echo “Google is online” prints a message indicating that Google is online).

break command exits the infinite loop if the website is reachable.

fi marks the end of the if statement.

sleep 10 introduces a 10-second pause using the sleep command before the loop iterates again.

Example #5: Anticipate Latency

The sleep command is a valuable tool for managing latency in specific situations. The following script snippet demonstrates how sleep provides the CPU adequate time to execute the calculation before proceeding to the next iteration.

for (( i = 1 ; i <= 250 ; i++ ));

    do

    sleep 1

    qsub computation"${i}".pbs

done

Here, for (( i = 1 ; i <= 250 ; i++ )); do initiate a for loop that repeats 250 times, assigning values from 1 to 250 to the variable i in each iteration.

sleep 1 introduces a one-second pause using the sleep command.

We recommend our tutorial on the Bash wait command that ensures similar capabilities in delayed command execution. 

Also Read: lsof Command in Linux with Examples

Also Read: Mastering the Linux tee Command for Redirecting Output In 9 Examples

Conclusion

Now that you have gone through the tutorial, you have gained an understanding of how to utilize the Linux sleep command to pause command execution within a sequence temporarily. 

At RedSwitches, we’re dedicated to helping you discover the perfect server solutions to drive your business to new heights. So, if you’re looking for a powerful server, we offer the best-dedicated server pricing and deliver instant dedicated servers, usually on the same day the order gets approved. Whether you need a dedicated server, a traffic-friendly 10Gbps dedicated server, or a powerful bare metal server, we are your trusted hosting partner.

For further guidance, consider resources like RedSwitches for comprehensive Linux infrastructure support.

FAQs

Q. What is the ‘sleep’ command in Linux, and how does it function?

The ‘sleep’ command in Linux is a command-line utility used to introduce a time delay in the execution of commands or scripts. It suspends the execution of the calling process for a specified time duration before proceeding further.

Q. Can I use the ‘sleep’ command in conjunction with other commands in a bash script?

Yes, the ‘sleep’ command can be used with other commands in bash scripts to introduce delays between command executions. This can be particularly useful for controlling the flow of script execution or allowing time for certain tasks to be completed before proceeding.

Q. Is the ‘sleep’ command suitable for creating infinite loops in bash scripts?

Yes, the ‘sleep’ command is often used in combination with loops to create infinite loops with controlled delays between iterations. This can be useful for tasks that require continuous monitoring or periodic execution.

Q. How can I use the ‘sleep’ command to prompt user interaction in a bash script?

You can utilize the ‘sleep’ command to introduce pauses in script execution, allowing time for user input or interaction. By strategically placing ‘sleep’ commands within your script, you can create a responsive and user-friendly experience.

Q. What is the basic syntax for using the ‘sleep’ command in Linux bash scripts?

The basic syntax for the ‘sleep’ command is straightforward: simply type ‘sleep’ followed by the desired sleep time, expressed in seconds or other units of time. For example, ‘sleep 10‘ will pause execution for 10 seconds.

Q. Can the ‘sleep’ command be used to control background processes in Linux?

Yes, the ‘sleep’ command can be used in conjunction with background processes to introduce delays or timeouts as needed. By incorporating ‘sleep’ into your scripts, you can effectively manage background processes within your current session.

Q. Why is the ‘sleep’ command considered an essential tool in Linux scripting?

The ‘sleep’ command is considered an essential and simple command tool in Linux scripting due to its versatility in controlling script execution and managing time delays. Whether used for basic tasks or complex scripting scenarios, the sleep command tool offers a simple yet effective solution for introducing delays and controlling script flow.

Q. How can the ‘sleep’ command be utilized for simple tasks in Linux scripting?

The ‘sleep’ command is often employed in simple bash scripts to introduce time delays between commands, allowing for smoother execution of sequential tasks. For example, it can be used to pause script execution before moving to the next task or to introduce delays in loops for controlled iteration.

Q. What are some practical examples showcasing the basic usage of sleep command in Linux scripting?

Simple examples of utilizing the ‘sleep’ command include creating simple bash scripts to automate repetitive tasks, such as file processing or system monitoring. By incorporating ‘sleep’ commands at strategic points within the script, you can ensure smooth execution and optimal resource utilization.

Q. How does the ‘sleep’ command serve as the perfect solution for introducing time delays in simple shell scripts?

The ‘sleep’ command offers a straightforward and efficient means of introducing time delays in simple shell scripts. Whether used to simulate real-world scenarios, control loop iteration, or implement timeouts, the ‘sleep’ command syntax and versatility make it an indispensable tool for scripting tasks.

Q. How does the ‘sleep’ command contribute to executing advanced shell scripts in Linux?

The ‘sleep’ command is essential in advanced shell scripting for precise timing control. It allows scriptwriters to introduce delays, timeouts, and pauses, optimizing performance. For instance, in monitoring scripts, ‘sleep’ intervals between checks reduce resource usage. In complex background processes, ‘sleep’ synchronizes components and mitigates race conditions. Overall, ‘sleep’ enhances bash scripting by orchestrating processes seamlessly.

Try this guide with our instant dedicated server for as low as 40 Euros