How to Add Delays in Bash? [Sleep for a Time]

Delay in Bash refers to the pause or waiting period that is used to regulate the sequence of tasks or timing of operations within a script. It allows synchronizing script execution with external processes, introducing timeouts for specific actions, handling concurrency with efficient resource utilization and so on. In this article, you’ll find how to implement delays in Bash scripts using the sleep command in different time-controlling scenarios.

Understanding Delays in Bash

Delays are introduced to wait for a certain amount of time to pass before proceeding with the next command or task. The sleep command is the fundamental option for implementing delays in different ways and handling script execution in Bash. Let’s explore this fact!

Bash “sleep” Command

The sleep command is used to pause the execution of a command or script for a specified amount of time. This command is useful for any kind of scheduled task. The basic syntax for the sleep command in Bash is:

sleep NUMBER [SUFFIX]

Here, NUMBER denotes the duration of the delay which can be either a positive integer or a fractional number. [SUFFIX] is an optional part where you can use any options mentioned in the following table:

SUFFIX Example
s (Seconds) sleep 5  #Sleep for 5 seconds

Or,

sleep 5s  #Sleep for 5 seconds

m (Minutes) sleep 9m  #Sleep for 9 minutes
h (Hours) sleep 1h  #Sleep for 1 hour
d (Days) sleep 3d  #Sleep for 3 days

Note: By default, the NUMBER is considered to be in seconds (s) when no suffix is applied after it.

Sleep Infinity

To indefinitely pause the execution of a command or script in Bash (until any explicit termination), use the argument ‘infinity’ with the sleep command.

sleep infinity

4 Practical Examples of Delay Using “sleep” in Bash Script

Mastering delay and time is crucial for managing complex tasks or handling resources for various scenarios. In this exploration, I’ll delve into 4 different practical examples of implementing delays such as using background processes, loops, conditional statements, and fractional seconds in Bash scripts.

Example 1: Background Processes with Different Delays

In Bash, multiple processes can be started concurrently in the background, each with its own specified delay represented by the sleep command.

To understand how to execute all the background processes with different delays in parallel, check out the following script:

#!/bin/bash

process_perform() {
process=$1
delay=$2
echo "Initializing $process"
sleep "$delay"
echo "$process completed with $delay seconds delay"
}

#Processes in the background with different delays
process_perform "Process 1" 2 &   #process 1 with 2 seconds delay
process_perform "Process 2" 3 &   #process 2 with 3 seconds delay
process_perform "Process 3" 1 &   #process 3 with 1 second delay

#Waiting for all background processes to complete
wait

echo "Completed all processes"
EXPLANATION

Inside the function process_perform, process=$1, delay=$2 and sleep "$delay" represent the process name, delay in seconds and the specified delay respectively. Then, the three instances of the process_perform function are called in the background (using &) with different delay durations. The wait command here pauses the script execution and waits for all the background processes to complete. Finally, the script displays an output message after all the process completions.

Completed multiple background processes with different delays using "sleep" command in Bash

This image represents the output of the parallel execution of background processes with different durations.

Example 2: Dynamic Delays with Loops

The dynamic delay is the delay whose duration is determined based on runtime conditions. It can be achieved by fetching values from external sources, evaluating expressions, varying certain iterations within a loop, etc.

Here’s an example introducing dynamic delays with a loop in Bash:

#!/bin/bash

#A function to perform a task with dynamic delays
dynamic_delays() {
for (( n=1; n<=3; n++ )); do
echo "Task $n launching..."
sleep $((n * 2))  #Dynamic delays based on iteration number
echo "Completed task $n"
done
}

#Calling the function
dynamic_delays
EXPLANATION

Here, the function dynamic_delays performs a task for 3 times using a for loop. Inside the loop,  sleep $((n * 2)) demonstrates the delay for each task is dynamically calculated based on n (iteration number) where the delay increases by a factor of 2 seconds for each iteration.

Output of task completion introducing dynamic delays with loops

The above image demonstrates the incorporation of dynamic delays into a task within a for loop.

Example 3: Timeouts with Conditional Statements

In Bash scripting, the sleep command can be used with conditional statements to implement timeouts efficiently. It allows executing tasks within a specific time duration as well as handling situations when tasks exceed the allotted time for completion.

Navigate through the following script to implement timeouts with the sleep command and conditional statements:

#!/bin/bash

timeout_task() {
timeout=3  #Timeout duration in seconds

#Starting a background process
sleep 8 &
process_pid=$!
sleep $timeout #Sleeping for a specific timeout duration

#Checking if the process is still running
if ps -p $process_pid > /dev/null; then
  #Killing the task and printing a timeout message
  kill $process_pid
  echo "Process exceeds time."
else
  echo "Process completed within $timeout seconds."
fi
}

#Calling the function
timeout_task
EXPLANATION

Here, the timeout_task sets a timeout duration of 3 seconds and starts a background process sleep 8 & that sleeps for 8 seconds. The process_pid=$! holds the PID (Process ID) of the background process.  After 3 seconds of sleep, the script checks if the background is still running. If it is running, it means it exceeds the timeout duration and the script terminates the process using kill $process_pid with an output message. Otherwise, the script displays a message indicating the successful completion of the process before the timeout duration.

The process execution exceeds the timeout duration

As you can see in the image the output message ‘Process exceeds time.’, it means that the background process (sleep 8 &) takes longer than the specified timeout duration (3 seconds).

Example 4: Delay with Fractional Seconds Using “sleep” and “bc” Command

To introduce delays with fractional seconds, you can use the sleep command. As Bash itself doesn’t support floating point arithmetic, use the bc command to have precise control over timing in scripts. Here’s how to implement delays with fractional seconds using the bc command in Bash:

#!/bin/bash

#Defining delay in fractional seconds
delay=0.7

#Calculating delay in milliseconds
ms_delay=$(echo "$delay * 1000" | bc)

echo "Delay: $ms_delay milliseconds"

#Using delay with 'sleep' command
sleep "$delay"

echo "Displaying this message after $delay seconds of delay."

EXPLANATION

Here, delay=0.7 sets the duration of the delay in fractional seconds (0.7 seconds). Then, delay_ms=$(echo "$delay * 1000" | bc) converts the delay to milliseconds by multiplying the delay value (0.7) with 1000 using the bc command. In sleep  "$delay", the sleep command pauses the script to execute for a specified duration stored in the $delay variable. Finally, after the delay the script prints an output message indicating that the delay has been completed.

Displaying output of fractional seconds of delay in Bash

From the image, you can see that the delay of 0.7 seconds is converted into 700 milliseconds using the bc command and after the delay duration, an output message is displayed for confirmation.

Conclusion

To conclude, incorporating delays provides flexibility and reliability while handling various scenarios effectively in Bash scripts. Whether you want to wait for processes in the background, manage script execution or set retry policies, using delays with sleep command allows you to achieve accurate control over timing and improve your scripts’ performance.

People Also Ask

Can I use fractions of seconds with the sleep command?

Yes, you can use fractions of seconds with the sleep command. For example:

sleep 0.5  #Pauses execution for 0.5 seconds.

Is it possible to interrupt the sleep process?

Yes, it is possible to interrupt the sleep process and continue the script execution by pressing CTRL + C and sending a SIGINT (Interrupt) signal to the script or command.

Can I use sleep and wait together to achieve delays?

Yes, you can use the sleep and wait commands together to achieve delays in Bash where the sleep command introduces the desired delay and the wait command waits for all the background processes to complete. For example:

#!/bin/bash

#Launching multiple processes
sleep 2 &
sleep 3 &
sleep 4 &

echo "Multiple background processes are running"

#Introducing a delay
sleep 1

#Waiting for the background processes to finish
wait %1 %2 %3

echo "Process execution completed!"

Can I use variables with the sleep command?

Yes, you can use variables with the sleep command to specify the duration dynamically. For example:

#!/bin/bash

#Setting the time of the delay in seconds using a variable
delay=3

#Pausing the script execution for the duration stored in the 'delay' variable
sleep "$delay"

Do “sleep” and “wait” commands have different use cases?

Yes, the sleep command is used for intentional pauses or delays that directly affect the execution of the script for a specified duration whereas the wait command is used to pause the script until all the background processes are finished which doesn’t affect the script’s execution directly.

Is there a way to interrupt the execution of a script that is waiting using wait?

Yes, by sending an interrupt signal (SIGINT), you can interrupt the execution of a script that is waiting using wait. To send the interrupt signal, use the short key CRTL + C and this will terminate any process or script’s execution instantly.

Related Articles


<< Go Back to Process Management in Bash | Bash Process and Signal Handling | Bash Scripting Tutorial

Rate this post
LINUX
FUNDAMENTALS
A Complete Guide for Beginners Enroll Course Now
icon linux

Nadiba Rahman

Hello, This is Nadiba Rahman, currently working as a Linux Content Developer Executive at SOFTEKO. I have completed my graduation with a bachelor’s degree in Electronics & Telecommunication Engineering from Rajshahi University of Engineering & Technology (RUET).I am quite passionate about crafting. I really adore exploring and learning new things which always helps me to think transparently. And this curiosity led me to pursue knowledge about Linux. My goal is to portray Linux-based practical problems and share them with you. Read Full Bio

Leave a Comment