Bash Sleep


Bash Sleep

In Bash scripting, the sleep command is used to pause the execution of a script for a specified duration. This is useful for creating delays, scheduling tasks, and managing timing in scripts.


Syntax

The basic syntax for the sleep command is:

sleep duration

The duration can be specified in seconds, minutes, hours, or days by appending s, m, h, or d to the number.


Example Bash Sleep

Let's look at some examples of how to use the sleep command in Bash:

1. Sleep for a Few Seconds

This command pauses the script for 5 seconds.

#!/bin/bash

# Sleep for 5 seconds
sleep 5
echo "5 seconds have passed"

In this example, the script pauses for 5 seconds before printing the message.

Sleep for 5 seconds in Bash

2. Sleep for a Few Minutes

This command pauses the script for 2 minutes.

#!/bin/bash

# Sleep for 2 minutes
sleep 2m
echo "2 minutes have passed"

In this example, the script pauses for 2 minutes before printing the message.

Sleep for 2 minutes in Bash

3. Sleep for Hours

This command pauses the script for 1 hour.

#!/bin/bash

# Sleep for 1 hour
sleep 1h
echo "1 hour has passed"

In this example, the script pauses for 1 hour before printing the message.

Sleep for 1 hour in Bash

4. Sleep for Days

This command pauses the script for 1 day.

#!/bin/bash

# Sleep for 1 day
sleep 1d
echo "1 day has passed"

In this example, the script pauses for 1 day before printing the message.

Sleep for 1 day in Bash

5. Sleep with Mixed Durations

This command pauses the script for a mixed duration of 1 minute and 30 seconds.

#!/bin/bash

# Sleep for 1 minute and 30 seconds
sleep 1m 30s
echo "1 minute and 30 seconds have passed"

In this example, the script pauses for 1 minute and 30 seconds before printing the message.

Sleep for 1 minute and 30 seconds in Bash

Using Sleep in Scripts

The sleep command can be used in scripts to create delays between commands, simulate processing time, or schedule repeated tasks.

#!/bin/bash

# Print message
echo "Starting process..."

# Sleep for 3 seconds
sleep 3

# Print message
echo "Process completed after 3 seconds"

In this example, the script prints a message, pauses for 3 seconds, and then prints another message.

Using sleep in scripts in Bash

Conclusion

Using the sleep command in Bash is essential for pausing script execution for a specified duration. It is useful for creating delays, scheduling tasks, and managing timing in shell scripts. Understanding how to use the sleep command with different durations can help you write more effective and controlled Bash scripts.